Question

I have been battling this test way too long and I am not sure where I am stuck. Here is the model I am trying to test:

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

  def genius?
    iq >= 3
  end

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

Here is what I am working with to start:

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

This is the part of the refactor that is working:

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

Here is where I am currently stuck at with the refactor:

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

According to the examples this should work, but no matter what I try it keeps bombing on the include. I know I am missing something lame here. Thoughts or tips anyone?

Current Error Message:

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
Was it helpful?

Solution

You need to add the ! to the let and change new to create in order to save the record.

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

OTHER TIPS

I'm not sure what examples you are referring to that suggest your refactor should work, but the implicit subject zombie used in your first refactored example is an ActiveRecord instance and the include matcher you're using is intended to be used with a string, array or hash as described in https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/include-matcher.

As for your second refactored example, I gather it's working because you've only indicated a problem with the include.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top