Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rspec rails mocking session hash

I am trying to mock out the session hash for a controller like so:

it "finds using the session[:company_id]" do
  session.should_receive(:[]).with(:company_id).and_return 100
  Company.should_receive(:find).with(100)
  get 'show'
end

When I call get 'show' it states:

received :[] with unexpected arguments  
expected: (:company_id)  
   got: ("flash")

The controller code looks like:

def show
  company_id = session[:company_id]
  @company = Company.find params[company_id]
end

I have also simply tried setting

it "finds using the session[:company_id]" do
  session[:company_id]= 100
  Company.should_receive(:find).with(100)
  get 'show'
end

but then get an issue about:

expected: (100)
got: (nil)

Anyone have ideas why?

like image 851
Adam T Avatar asked Sep 12 '10 03:09

Adam T


2 Answers

I just ran into this. I couldn't manage to get should_receive to not interfere with the flash stuff.

But this let me test the behavior I was looking for:

it "should redirect to intended_url if set" do
  request.env['warden'] = double(:authenticate! => true)
  session.stub(:[]).with("flash").and_return double(:sweep => true, :update => true, :[]= => [])
  session.stub(:[]).with(:intended_url).and_return("/users")
  post 'create'
  response.should redirect_to("/users")
end

Hope that helps...

like image 163
stuartc Avatar answered Nov 13 '22 06:11

stuartc


I could not figure out how to mock the session container itself, however in most cases simply passing session data with request should be enough. So the test would split into two cases:

it "returns 404 if company_id is not in session" do
  get :show, {}, {}
  response.status.should == 404 # or assert_raises depending on how you handle 404s
end

it "finds using the session[:company_id]" do
  Company.should_receive(:find).with(100)
  get :show, {}, {:company_id => 100}
end

PS: forgot to mention I'm using some customized helpers from this snippet.

like image 36
Tadas Sasnauskas Avatar answered Nov 13 '22 06:11

Tadas Sasnauskas