开发者

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
 开发者_C百科 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?


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...


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.


try this:

session.expects(:[]).with(has_entries('company_id' => 100))


It's because you fetch flash session from your controller. So define it. Flash is save in session.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜