使用rspec codechool 3级测试进行测试5

时间:2014-04-04 02:54:05

标签: ruby ruby-on-rails-3 rspec tdd

我一直在与这种测试方式作斗争太长时间,我不知道我被困在哪里。这是我试图测试的模型:

class Zombie < ActiveRecord::Base
  attr_accessible :iq
  validates :name, presence: true

  def genius?
    iq >= 3
  end

  def self.genius
    where("iq >= ?", 3)
  end
end

以下是我正在开始的工作:

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

这是重构的一部分:

 it { should be_genius }
 #it "should have a genius count of 1" do     
 #  Zombie.genius.count.should == 1
 #end

以下是我目前坚持使用重构的地方:

describe Zombie do
  context "with high iq" do
    let!(:zombie) { Zombie.new(iq: 3, name: 'Anna') }
    subject { zombie }

        it  {should include("zombie")}
        it { should be_genius }

  end
end

根据这些例子,这应该可行,但无论我尝试什么,它都会继续轰炸包含。我知道我在这里遗失了一些蹩脚的东西。任何想法或提示?

当前错误消息:

Failures:

1) Zombie with high iq 
Failure/Error: it {should include("zombie")}
NoMethodError:
undefined method `include?' for #<Zombie:0x00000006792380>
# zombie_spec.rb:7:in `block (3 levels) '

Finished in 0.12228 seconds
2 examples, 1 failure

Failed examples:

rspec zombie_spec.rb:7 # Zombie with high iq

2 个答案:

答案 0 :(得分:3)

您需要将!添加到let并将new更改为create才能保存记录。

describe Zombie do
  context "with high iq" do
  let!(:zombie) { Zombie.create(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

答案 1 :(得分:1)

我不确定您指的是哪些示例建议您的重构应该有效,但您的第一个重构示例中使用的隐式主题zombie是ActiveRecord实例,而include匹配器是您re using用于与https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/include-matcher中描述的字符串,数组或散列一起使用。

关于你的第二个重构示例,我认为它正在运行,因为你只是指出了include的问题。