2

Using Rails 3.0.5, RSpec 2 and Capybara 0.4.1.2 and I'am trying to write a controller spec for my SessionsController#new action.

it "assigns the empty session to a variable" do
  get :new
  assigns(:session).should == ActiveRecord::Base::Session.new
end

I'm using the ActiveRecord::Base namespace as it seems to clash with the Capybara Session class when I don't.

Here is the SessionsController:

class SessionsController < ApplicationController
  def new
     @session = Session.new
  end
end

RSpec doesn't seem to understand these are the same objects. Here is what my test returns:

 Failure/Error: assigns(:session).should == ActiveRecord::Base::Session.new
   expected: #<Session id: nil, session_id: nil, data: nil, created_at: nil, updated_at: nil>
        got: #<Session id: nil, session_id: nil, data: nil, created_at: nil, updated_at: nil> (using ==)
   Diff:
 # ./spec/controllers/sessions_controller_spec.rb:17:in `block (3 levels) in <top (required)>'

Any hints?

Cimm
  • 4,653
  • 8
  • 40
  • 66

1 Answers1

3

The problem is that if you do

ActiveRecord::Base::Session.new == ActiveRecord::Base::Session.new

You would get false, as both these objects have a separate object_id.

Try this:

assigns(:session).should be_an(ActiveRecord::Base::Session)
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Thanks, this works. Out of curiosity... would it make a difference if I use `be_an` or `be_an_instance_of` here? – Cimm Mar 27 '11 at 10:35
  • Ah yes. `be_an` checks for `kind_of?` and `be_an_instance_of` checks for `instance_of?`. So be_an will also be true for every instance of any class that inherits from AR::Base::Session. More info: http://stackoverflow.com/questions/3893278/ruby-kind-of-vs-instance-of-vs-is-a – Dogbert Mar 27 '11 at 10:41
  • You could also use the #inspect method to compare the contents of the two objects. `assigns(:session).inspect.should == ActiveRecord::Base::Session.new.inspect`. – Chris Bloom Mar 20 '12 at 17:08