未能通过 rspec 测试
Lost trying to make the rspec test pass
我有这个class:
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){...}
但它告诉我当我期望 1 时得到 0。有什么想法吗?也许我花了很多时间查看这段代码,但我没有看到问题出在哪里。
您需要 Zombie.create
而不是 Zombie.new
。
此外,should
语法已弃用:
specify ".genius returns an array of zombies" do
expect(Zombie.genius).to include(zombie)
end
我觉得这条线
let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
应该是
let!(:zombie) { Zombie.create(iq: 3, name: 'Anna') }
为什么?因为 create 确保将僵尸实例保存到数据库中,所以当您查询 iq >= 3 时,您会得到一个僵尸实例。 new 我相信只保留僵尸实例在内存中。
我有这个class:
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){...}
但它告诉我当我期望 1 时得到 0。有什么想法吗?也许我花了很多时间查看这段代码,但我没有看到问题出在哪里。
您需要 Zombie.create
而不是 Zombie.new
。
此外,should
语法已弃用:
specify ".genius returns an array of zombies" do
expect(Zombie.genius).to include(zombie)
end
我觉得这条线
let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
应该是
let!(:zombie) { Zombie.create(iq: 3, name: 'Anna') }
为什么?因为 create 确保将僵尸实例保存到数据库中,所以当您查询 iq >= 3 时,您会得到一个僵尸实例。 new 我相信只保留僵尸实例在内存中。