這是我的第一個問題,我實際上在問,因爲我很絕望,我的課程的導師不在了......我正在關注一個web開發課程並遇到了這個問題使用RSpec進行單元測試的問題...我使用的命令行是rspec spec/models(並且該文件夾中的文件是:product_spec.rb)。這是我使用的測試代碼:這個rspec失敗代碼有什麼問題
require 'rails_helper'
describe Product do
context "when the Product has comments" do
before do
@product = Product.create(:name => "product model")
end
end
context "when user has email & password" do
before do
@user = User.create(:email => "[email protected]", :password => "passtheword")
end
end
context "create comment 1" do
before do
@product.comments.create(:rating => 1, :user => @user, :body => "Awful comment!")
end
end
context "create comment 2" do
before do
@product.comments.create(:rating => 3, :user => @user, :body => "another awful comment!")
end
end
context "create coment 3" do
before do
@product.comments.create(:rating => 5, :user => @user, :body => "yet another awful comment!")
end
end
context "rating average" do
before { @average_rating = Product.comments.count(:rating) }
it "returns the average rating" do
expect(@average_rating).to eq 3
end
end
end
這是我從RSpec的發現了錯誤:
F
Failures:
1) Product rating average returns the average rating
Failure/Error: before { @average_rating = Product.comments.count(:rating) }
NoMethodError:
undefined method `comments' for #<Class:0x007fe22e58b6d8>
# ./spec/models/product_spec.rb:43:in `block (3 levels) in <top (required)>'
Finished in 0.00099 seconds (files took 1.61 seconds to load)
1 example, 1 failure
Failed examples:
rspec ./spec/models/product_spec.rb:44 # Product rating average returns the average rating
我甚至嘗試宣告的「評論」像這樣:
context "register comment" do
before do
@comments = @product.comments
end
end
但是這沒有什麼區別。任何關於此事的幫助將非常感激,因爲我瘋了,並在過去的3天中在計算機附近砸碎了東西!接下來的事情是粉碎電腦本身! 非常感謝您的閱讀。希望你過得愉快。
哦!忘了補充一點,我應該測試提交的評論的平均評分,但不要使事情複雜化,在現階段,如果代碼返回提交了多少評論/評分,我會很高興;因此= 3仍然有效,因爲評分1 + 3 + 5/3仍然給出3.謝謝。 – TYX