【问题标题】:Testing with Rspec codeschool level 3 challenge 5使用 Rspec codeschool 3 级挑战 5 进行测试
【发布时间】:2014-04-04 02:54:05
【问题描述】:

我已经与这个测试作斗争太久了,我不确定我在哪里卡住了。这是我要测试的模型:

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

【问题讨论】:

  • 问问自己:在你的两个例子中,“它”代表什么?

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


【解决方案1】:

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

【讨论】:

  • 太棒了。非常感谢你的帮助,我已经坚持了好几个小时了。
【解决方案2】:

我不确定您指的是哪些示例表明您的重构应该起作用,但是在您的第一个重构示例中使用的隐式主题 zombie 是 ActiveRecord 实例,而您正在使用的 include 匹配器旨在与https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/include-matcher 中所述的字符串、数组或哈希一起使用。

至于您的第二个重构示例,我认为它可以正常工作,因为您只指出了 include 的问题。

【讨论】:

  • be_genius 应该可以工作; RSpec 为以? 结尾的任何内容构建谓词匹配器,因此be_whatever 应该在实例上调用whatever?。不过,我认为这并不总是好的风格。
  • 我调整了我觉得正在工作的东西,那就是 be_genius。问题仍然在于包含或测试“僵尸”是否包含在天才中......想法?
  • 另外,我刚刚重新运行了测试,以便将特定的输出转储给您。
  • @chrishough 在原始代码中,主题是明确的:Zombie.genius。这将返回一个集合,该集合响应 include。重构将主题更改为Zombie.new,这是一个实例,而不是一个集合——它不响应include。您需要将第一个示例的主题更改为Zombie.genius。这也表明使用隐式主题并不总是一个好主意。我还认为您需要保存实例以便where 范围找到它。
  • @zetetic 将主题重构为:subject { Zombie.genius } 没有任何效果。谢谢你的帮助,我很感激这个人。还有其他提示吗?如果我改变主题,我将如何改变测试?
猜你喜欢
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 2022-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 2017-07-22
相关资源
最近更新 更多