如何在水豚测试中使用Rspec扼制Warden / Devise [英] How to Stub out Warden/Devise with Rspec in Capybara test

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

问题描述

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



以前,我能够使用authlogic这样做,会话模型有一些这样的代码:

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

现在我正在使用Devise,我不能再访问UserSession对象。而且,由于我使用capybara来测试我的代码,所以我没有直接访问请求对象来使用devise内置的 sign_in test helper。



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

解决方案

监狱长内置测试助手。它允许您登录,而不必在黄瓜测试中使用UI。只需将以下文件添加到您的项目中。



#features / support / warden.rb

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

#features / step_definitions / user_steps.rb

 给定/ ^我以用户身份登录$ / do 
@current_user = User.create!( :username =>'user',:password =>'password')
login_as(@current_user,:scope =>:user)
end

使用Wardens.test_mode!与水豚一起


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.

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

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 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

Use Wardens.test_mode! with Capybara

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

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