【发布时间】:2015-12-01 12:03:45
【问题描述】:
这是我在这里的第一个问题,我实际上是在问,因为我很绝望,我的课程导师不在……我正在学习一个 Web 开发课程,并在使用 RSpec 进行单元测试时遇到了这个问题。 .我使用的命令行是rspec spec/models(该文件夹中的文件是:product_spec.rb)。这是我用来测试的代码:
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 => "testspec@test.com", :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
我什至尝试过这样声明“cmets”:
context "register comment" do
before do
@comments = @product.comments
end
end
但这并没有什么不同。任何关于此事的帮助将不胜感激,因为我快疯了,过去 3 天在电脑附近砸东西!接下来就是砸电脑了!! 非常感谢您的阅读。希望你今天过得愉快。
【问题讨论】:
-
哦!!忘了补充,我应该测试提交的 cmets 的平均评分,但不要让事情复杂化,在这个阶段,如果代码返回已提交的 cmets/评分数,我会很高兴;因此 =3 仍然有效,因为等级 1 + 3 + 5 / 3 仍然给出 3。谢谢。
标签: rspec