ruby - 使用 Rspec codeschool 3 级挑战 5 进行测试

标签 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

最佳答案

您需要将 ! 添加到 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

关于ruby - 使用 Rspec codeschool 3 级挑战 5 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22852656/

相关文章:

ruby - 具有已知色数的图形生成器

ruby-on-rails - 单个延迟作业 worker 可以在正在进行的作业结束之前开始下一个作业吗?

ruby-on-rails - 当关联在 View 中延迟加载时引发异常

ruby-on-rails - 如何分析我的 rspec 测试以找到最大的内存消耗?

ruby-on-rails - 为 Stripe::Error 创建 Error 对象 (Ruby on Rails)

ruby-on-rails - rails new project_name 使用 rvm

ruby-on-rails - 通过 Ajax Rails 调用辅助方法

ruby - Rails——before_save 不工作?

ruby-on-rails - RoR 和 RSpec : How to access controller instance variables without defining accessors?

ruby-on-rails - 在 'require' : no such file to load -- spec_helper