我有这门课:

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

10-08 16:16