rspec Rails 模拟会话哈希
我试图模拟控制器的会话哈希,如下所示:
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)
有人知道为什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我刚刚遇到了这个。我无法设法让 should_receive 不干扰闪存的东西。
但这让我测试了我正在寻找的行为:
希望有帮助......
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:
Hope that helps...
我不知道如何模拟会话容器本身,但是在大多数情况下,只需通过请求传递会话数据就足够了。因此测试将分为两种情况:
PS:忘记提及我正在使用此片段中的一些自定义帮助器。
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:
PS: forgot to mention I'm using some customized helpers from this snippet.
试试这个:
try this:
这是因为您从控制器获取闪存会话。所以定义它。 Flash 保存在会话中。
It's because you fetch flash session from your controller. So define it. Flash is save in session.