问题描述
我在测试控制器和使用 Warden 时遇到问题.
I'm having an issue with testing my controllers and using Warden.
所有示例都指向存根 request.env['warden']
.当我调用 env['warden']
时,这会导致我的控制器出现问题,然后返回 nil
.
All examples point at stubbing request.env['warden']
. This causes issues in my controllers when I call env['warden']
, which then returns nil
.
举个粗略的例子,使用这个:
For a crude example, using this:
request.env['warden'] = double(Warden, :authenticate => nil,
:authenticate! => nil,
:authenticated? => false)
还有一个像这样的简单前置过滤器:
And a simple before filter like this:
before_filter do
redirect_to new_user_session_url unless env['warden'].authenticated?
end
我得到一个 nil
.
我只是设法使用 controller.env['warden'] = ...
让它工作,并且它工作正常.这是有道理的,因为它位于控制器级别,所以我想我的问题是它在我看过的所有示例中不起作用.
I just managed to get it working using controller.env['warden'] = ...
and it works.This makes sense, since it's sitting right at the controller level, so I guess my question is what wouldn't it work in the I've seen all examples.
我的 spec_helper
中有这个:
config.include Warden::Test::Helpers
任何帮助都会很棒!
推荐答案
尽管有很多示例告诉您在 Rails 应用程序中通过 env['warden']
实现 Warden.通过 request.env['warden']
访问它似乎是正确的方法.
Despite many examples telling you to implement Warden through env['warden']
in your Rails app. It seems the correct way to access it through request.env['warden']
.
它通过在测试期间在我的控制器中提升 env 发现了这一点,并且总是 nil
.
It found this out by raising env in my controllers during tests, and this always came out nil
.
好像在Warden,https://github.com/hassox/warden/blob/master/lib/warden/proxy.rb#L13机架环境有一个访问器,由于在控制器测试中没有机架,它在测试模式下不存在.请有人检查一下.
It seems in Warden, https://github.com/hassox/warden/blob/master/lib/warden/proxy.rb#L13There is an accessor for the rack environment, which won't exist in test mode due to the absence of Rack in controller tests. Please someone check this.
因此,当在 RSpec 中存根 request.env
时,您的实现需要指向 request.env
.
So when stubbing request.env
in RSpec, your implementation needs to point at request.env
.
在我看来,这似乎是一种必要的邪恶.但如果有人有好的解释或解决方法,我很乐意继续讨论.
It seems a necessary evil in my mind. But if there is anyone with a good explanation or work around, I'd love to continue this discussion.
这篇关于在控制器测试中存根监狱长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!