Testing the ruby ​​session decoder lib on rails with rspec

I have this code in lib / user_session.rb

It is used by one of my controllers through include UserSession.

How can I check it? I added tests to spec / lib / user_session.rb, but the code relies on a session that I'm not sure how to taunt.

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 
+4
source share
2 answers

You need to ridicule or silence the [] operator in the session. For example, in your specification, you can:

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

or

 session.should_receive(:[]).with(:viewed) 
+1
source

As far as I understand from your code, you do not rely on a session as much as you rely on an object that corresponds to the basic interface in the form of a bracket reader.

Now I don’t use RSpec, so I couldn’t say exactly how to use it in this scenario, but I would create a mock class using the parenthesis instance method or even a hash, and then check against this object, for example

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

Hope this helps.

+1
source

All Articles