【问题标题】:Lost trying to make the rspec test pass试图通过 rspec 测试失败
【发布时间】:2015-07-08 00:34:25
【问题描述】:

我有这门课:

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.count.should == 1

标签: ruby-on-rails ruby testing rspec rspec2


【解决方案1】:

您需要Zombie.create 而不是Zombie.new

另外,should 语法已被弃用:

specify ".genius returns an array of zombies" do
  expect(Zombie.genius).to include(zombie)
end

【讨论】:

    【解决方案2】:

    我认为这条线

    let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
    

    应该是

    let!(:zombie) { Zombie.create(iq: 3, name: 'Anna') }
    

    为什么?因为 create 确保僵尸实例被保存到数据库中,所以当您查询 iq >= 3 时,您会得到一个僵尸实例。 new 我相信只会将僵尸实例保存在内存中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多