我有这堂课:
class Zombie < ActiveRecord::Base
attr_accessible :iq
validates :name, presence: true
def genius?
iq >= 3
end
def self.genius
where("iq >= ?", 3)
end
end
我正在进行rspec测试:
describe Zombie do
context "with high iq" do
let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
subject { zombie }
it "should be returned with genius" do
Zombie.genius.should include(zombie)
end
it "should have a genius count of 1" do
Zombie.genius.count.should == 1
end
end
end
我收到此错误消息:
Failures:
1) Zombie with high iq should have a genius count of 1
Failure/Error: Zombie.genius.count.should == 1
expected: 1
got: 0 (using ==)
# zombie_spec.rb:11:in `block (3 levels) '
Finished in 0.2138 seconds
2 examples, 1 failure
Failed examples:
rspec zombie_spec.rb:10 # Zombie with high iq should have a genius count of 1
我正在使用语法:let!(:zombie){...}
但它告诉我在预期时得到0 1.任何想法?也许我已经花了很多时间来查看这段代码而且我不知道问题出在哪里。
答案 0 :(得分:2)
您需要Zombie.create
而不是Zombie.new
。
此外,不推荐使用should
语法:
specify ".genius returns an array of zombies" do
expect(Zombie.genius).to include(zombie)
end
答案 1 :(得分:1)
我想这一行
let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
应该是
let!(:zombie) { Zombie.create(iq: 3, name: 'Anna') }
为什么呢?因为 create 可以确保将僵尸实例保存到数据库中,所以当你对iq&gt; = 3进行查询时,你会得到一个僵尸。 new 只会将zombie实例保留在内存中我相信。