本文介绍了对控制器测试进行监督的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试控制器和使用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.

使用一个粗略的例子:

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.

在监狱长看来, 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.

这篇关于对控制器测试进行监督的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 06:55