Ruby on rails rspec rails模拟会话哈希
我试图模拟控制器的会话哈希,如下所示:Ruby on rails rspec rails模拟会话哈希,ruby-on-rails,rspec,rspec2,Ruby On Rails,Rspec,Rspec2,我试图模拟控制器的会话哈希,如下所示: 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 当我调用get“show”时,它表示: received :[] with unexpected arguments e
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
当我调用get“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)
有人知道为什么吗?这是因为您从控制器获取闪存会话。所以定义它。闪存保存在会话中
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
试试这个:
session.expects(:[]).with(has_entries('company_id' => 100))
我刚碰到这个。我没办法让你收到的东西不干扰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
希望这会有所帮助……我不知道如何模拟会话容器本身,但是在大多数情况下,仅通过请求传递会话数据就足够了。因此,测试将分为两种情况:
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:忘了提到我正在使用来自的一些自定义帮助程序。我尝试了此操作,但仍然出现错误1)CompanyController使用会话[:company\u id]获取“show”查找失败/错误:为nil:NilClass#/Users/adam/.rvm/gems/ruby-1.8.7-p299/gems/activesupport-3.0.0/lib/active_support/whiny_nil.rb:48:inmethod_missing'…
会话中的变量在发出请求(get)之前不可用。这行不通。以下是我对这个问题的回答: