views:

433

answers:

2

I have this code in lib/user_session.rb

Its used by one of my controllers via include UserSession.

How can I test it? I've added tests in spec/lib/user_session.rb but the code relies on the session which I'm not sure how to mock.

module UserSession
  def viewed
    session[:viewed] ||= Array.new
    return session[:viewed]
  end

  def viewed_add(id, name)
    if viewed.select{|b| b[:id] == id}.empty?
      session[:viewed] << {:id => id, :name => name}
    end
    return session[:viewed]
  end

  def viewed_delete(id)
    unless id.nil?
      session[:viewed].delete_if{|b| b[:id] == id}
      return session[:viewed]
    end
  end
end
+1  A: 

As far as I can see from your code, you don't rely on the session so much as you rely on an object that conforms to a basic interface in the form of a bracket reader.

Now, I don't use RSpec myself so I couldn't say exactly how to use it in this scenario, but I'd create a mock class with a bracket reader instance method, or even a hash and then test against that object, e.g.

fake_session = { :viewer => nil }
class << fake_session
  include UserSession
end
assert_equal [], fake_session.viewer

Hope that helps.

darkliquid
+1  A: 

You need to mock or stub the [] operator on the session. For example, in your spec, you can do:

session.stub!(:[]).and_return "foo"

or

session.should_receive(:[]).with(:viewed)
Scott