使用 rspec 和 devise sign_in env 进行集成测试

发布于 12-10 09:49 字数 444 浏览 1 评论 0原文

我正在使用配置为使用omniauth facebook登录集成的设计。 当从我的 spec/request 测试中调用 sign_in 方法时,我得到:

undefined method `env' for nil:NilClass

spec:

describe FacebookController do
  include Devise::TestHelpers

  it "should display facebook logged in status" do
    @user = User.create(:id => "123", :token => "token")
    sign_in @user
    visit facebook_path
  end
end

I am using devise configured to use omniauth facebook sign in integration.
When calling the sign_in method from my spec/request tests I get:

undefined method `env' for nil:NilClass

spec:

describe FacebookController do
  include Devise::TestHelpers

  it "should display facebook logged in status" do
    @user = User.create(:id => "123", :token => "token")
    sign_in @user
    visit facebook_path
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮2024-12-17 09:49:34

你的代码看起来很像我的 - 我试图使用 Capybara 和 Devise TestHelper 函数,但事实证明你不能,按照 https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara。该页面上解释了推荐的方法,它对我有用。

需要明确的是,这就是我在 spec_helper.rb 中所做的:

RSpec.configure do |config|
  config.include Warden::Test::Helpers
end
Warden.test_mode!

在我的代码中,只需 - logout :user

根据 Devise wiki,您不能使用 sign_out 的原因如下:

如果您想知道为什么我们不能只使用 Devise 内置的sign_in 和sign_out 方法,这是因为这些方法需要直接访问请求对象,而使用Capybara 时这是不可用的。要将这两种方法的功能捆绑在一起,您可以创建一个辅助方法。

粗略地说,这意味着虽然使用 MiniTest 表示请求的对象 (@request) 作为实例变量添加到测试用例类中,但这并不意味着水豚不会发生这种情况。我没有查看代码来更准确地了解详细信息,但基本上,Warden 希望找到此对象,然后访问登录凭据所在的 cookie 存储。对于 Capybara/RSpec,我预计这种情况不会发生。

Your code looks a lot like mine - I was trying to use Capybara and the Devise TestHelper functions, and it turns out you can't, per https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara. The recommended way to do it is explained on that page, and it worked for me.

To be clear, here's what I did - in spec_helper.rb:

RSpec.configure do |config|
  config.include Warden::Test::Helpers
end
Warden.test_mode!

And in my code, simply - logout :user.

Here's why, according to the Devise wiki, you cannot use sign_out:

If you're wondering why we can't just use Devise's built in sign_in and sign_out methods, it's because these require direct access to the request object which is not available while using Capybara. To bundle the functionality of both methods together you can create a helper method.

Which, roughly, means that whereas with, say, MiniTest, an object representing the request (@request) is added as an instance variable to the test case class, that doesn't happen with Capybara. I haven't looked at the code to know the details more exactly but basically, Warden expects to find this object to then access the cookie store where the sign in credentials are. With Capybara/RSpec, I expect this isn't happening.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文