Search code examples
ruby-on-railsrspecrspec-rails

rSpec ==/eql can't compare the 'same' things


I have a controller index test that gets an ActiveRecord scope. The test currently looks like this (including some inline debugging stuff):

describe "GET index" do
  it "assigns all schools as @schools" do
    get :index
    puts assigns(:schools).class
    puts School.populated.class
    assigns(:schools).should == School.populated
  end
end

The output is this:

ActiveRecord::Relation
ActiveRecord::Relation

expected: []
     got: [] (using ==)
Diff:

This is definitely not the first time I've had this in recent versions of Rails and rSpec. Previously a coworker would just wrap the items in a to_a to compare them, which I find a bit dirty and likely not a good solution.

Any ideas? I'm curious as to why it thinks they are different, and how this same test passed in older versions of Rails and/or rSpec.


Solution

  • eql is the same as ==. Author of Rspec talks only do not use !=, use should_not instead

    actual.should == expected
    #is interpreted as this:
    
    actual.should.==(expected)
    
    #This is not true for !=. Ruby interprets this: actual.should != expected
    #as follows:
    
    !(actual.should.==(expected))
    

    Update: Relation provides Lazy Load pattern, so you do not have any executed query on the step. It means the fire the query on first request