我试图像这样模拟控制器的会话哈希:
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
当我打电话给'show'时,它说:
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 :(得分:4)
我刚碰到这个。我无法设法让miss_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
希望有帮助...
答案 1 :(得分: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中的一些自定义助手。
答案 2 :(得分:0)
试试这个:
session.expects(:[]).with(has_entries('company_id' => 100))
答案 3 :(得分:-1)
这是因为您从控制器获取Flash会话。所以定义它。 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