如何在 Capybara 测试中使用 Rspec 剔除 Warden/Devise [英] How to Stub out Warden/Devise with Rspec in Capybara test

查看:23
本文介绍了如何在 Capybara 测试中使用 Rspec 剔除 Warden/Devise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 Rails 应用程序的 Capybara 测试套件中使用 rspec 模拟来删除登录用户(使用 Devise/Warden).这将节省大量时间,并且意味着我的测试套件可以/将定期运行.

I want to stub out a logged in user (with Devise/Warden) using rspec mocks in a Capybara test suite in my Rails app. This would save a ton of time, and would mean that my test suite can/will be run regularly.

以前,我可以使用 authlogic 来完成此操作,方法是使用如下代码删除我的会话模型:

Previously I was able to do this using authlogic by stubbing out my session model with some code like this:

def login(user)
  user_session = mock_model(UserSession, {:user => user})
  UserSession.stub(:find).and_return(user_session)
end

现在我正在使用 Devise,我不再能够访问 UserSession 对象.由于我使用水豚来测试我的代码,因此我无法直接访问请求对象来使用设计的内置 sign_in 测试助手.

Now that i'm using Devise, i no longer have access to a UserSession object. And since i'm using capybara to test my code, i don't have direct access to the request object to use devise's built in sign_in test helper.

我的问题是:如何使用水豚、设计和规范模拟模拟登录用户,而不需要每个登录用户的场景都首先进入注册路径、填写表单、提交、等待响应,然后转到所需的页面?

My question is: how can I simulate a logged in user with capybara, devise, and spec mocks without requiring every scenario with a logged in user to first go to the sign up path, fill in the form, submit, wait for response, and then go to the desired page?

推荐答案

Warden 带有内置的测试助手.它使您无需在黄瓜测试中使用 UI 即可登录.只需将以下文件添加到您的项目中即可.

Warden comes with built in test helpers. It allows you to login without having to use the UI in your cucumber tests. Just add the files below into your project.

# features/support/warden.rb

Warden.test_mode!
World Warden::Test::Helpers
After { Warden.test_reset! }

# features/step_definitions/user_steps.rb

Given /^I am logged in as a user$/ do
  @current_user = User.create!(:username => 'user', :password => 'password')
  login_as(@current_user, :scope => :user)
end

使用 Wardens.test_mode!与水豚

这篇关于如何在 Capybara 测试中使用 Rspec 剔除 Warden/Devise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆