Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with "to" method in RSpec (undefined method)

Tags:

ruby

rspec

Completely new to rspec here, as will become evident.

The following rspec file fails:

require_relative( 'spec_helper')

describe GenotypingScenario do

  it 'should add genes' do
    scen = GenotypingScenario.new
    gene = Gene.new( "Pcsk9", 989 )
    scen.addGene( gene )
    expect( gene.id).to eq( 989 )
    ct = scen.genes.count
    expect (ct).to equal(1)
    expect (5).to eq(5)
  end
end

Specifically, the last two expect() lines fail, with errors like this:

NoMethodError: undefined method `to' for 1:Fixnum

Yet the first expect line works fine. And gene.id is definitely a FixNum.

Ruby 2.1.2, rspec 3.0.0, RubyMine on Mac OS 10.9.4.

Any thoughts?

like image 432
Steve Lane Avatar asked Aug 24 '14 16:08

Steve Lane


2 Answers

The spacing in your last two expect lines are tripping up the Ruby interpreter.

expect (5).to equal(1)

Is evaluated by Ruby as:

expect(5.to(equal(1)))

When what you really mean is:

expect(5).to(equal(1))

It's the return value from calling expect() that has a method to; RSpec isn't extending the Ruby built-in types. So you should change your last two expectations to read as follows:

expect(ct).to equal(1)
expect(5).to eq(5)
like image 144
Alex P Avatar answered Sep 17 '22 15:09

Alex P


I was following a Rails API tutorial with TDD, when I found a line in the tests that expected a json response not to be empty.

This is how I wrote it:

expect(json).not_to_be_empty

And I got that unfriendly NoMethodError: undefined method 'not_to_be_empty'

I came to the accepted answer on this thread and it opened my eyes.

I then changed the line to:

expect(json).not_to be_empty

I know you could still be looking for the difference, well, welcome to RSpec! I removed the underscore in between not_to and be empty to make two words. It worked like ... good code.

like image 27
Kaka Ruto Avatar answered Sep 17 '22 15:09

Kaka Ruto