2010-09-12 83 views
7

我试图模拟出会话哈希像这样的控制器:rspec的轨道嘲讽会议散列

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 

当我打电话得到“秀”它指出:

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

控制器代码样子:

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

我也只是尝试设置

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

但后来获得的一个问题:

expected: (100) 
got: (nil) 

任何人有任何想法,为什么?

+0

这是我对这个问题的回答: http://stackoverflow.com/questions/8043956/rspec-2-7-access-controller-session-in-spec-before-making-request/13369734#13369734 – 2012-11-13 22:12:54

回答

0

这是因为你从你的控制器获取闪存会话。所以定义它。 Flash保存在会话中。

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

我试过,但我仍然得到一个错误1) CompanyController GET '秀' 发现使用会话[:COMPANY_ID] 故障/错误:把 '节目' 的零 未定义的方法'扫”:NilClass #/用户/adam/.rvm/gems/ruby-1.8.7-p299/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:in'method_missing'... – 2010-09-12 22:42:55

1

试试这个:

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

我只是碰到了这一点。我无法设法让should_receive不会干扰flash内容。在大多数情况下

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 

希望帮助...

2

我无法弄清楚如何嘲笑会话容器本身,但是:

但是,这让我测试我一直在寻找的行为仅仅通过请求传递会话数据就足够了。因此,测试将分成两种情况:

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:忘了提,我使用了一些定制的助手从this snippet