与设计gem的Rails集成测试

我想写一个rails集成测试(使用ActionDispatch::IntegrationTest )。 我正在使用设计validation和机械师的测试模型。 我无法成功登录。

这是一个简单的例子:

 class UserFlowsTest  'foo@bar.com', :password => 'qwerty' p flash p User.all end 

这是调试输出:

 Loaded suite test/integration/user_flows_test Started {:alert=>"Invalid email or password."} [#, #] "/unauthenticated" F 

这是我的blueprints.rb:

 require 'machinist/active_record' require 'sham' User.blueprint do email {"foo@bar.com"} password {"qwerty"} end 

它不起作用的原因是设计创建表单字段名称为

 'user[email]' 'user[password]' 

和post_via_redirect期望这些名称作为参数。 因此,以下声明将成功登录。

 post_via_redirect 'users/sign_in', 'user[email]' => 'foo@bar.com', 'user[password]' => 'qwerty' 

首先,有了设计,您可能需要“确认”用户。

你可以这样做:

 user = User.make! user.confirmed_at = Time.now user.save! 

这是一个没有Machinist的例子(但你必须用上面的部分替换用户创建代码部分):

进入test_integration_helper:

 require "test_helper" require "capybara/rails" module ActionController class IntegrationTest include Capybara def sign_in_as(user, password) user = User.create(:password => password, :password_confirmation => password, :email => user) user.confirmed_at = Time.now user.save! visit '/' click_link_or_button('Log in') fill_in 'Email', :with => user.email fill_in 'Password', :with => password click_link_or_button('Sign in') user end def sign_out click_link_or_button('Log Out') end end end 

进入你的integration_test:

 require 'test_integration_helper' class UsersIntegrationTest < ActionController::IntegrationTest test "sign in and then sign out" do #this helper method is into the test_integration_helper file sign_in_as("lolz@gmail.com", "monkey") assert page.has_content?('Signed in successfully'), "Signed in successfully" sign_out assert page.has_content?('Signed out successfully'), "Signed out successfully" end end 

我在Devise的书中没有样本集成测试,但我认为如果安装了Webrat / Capybara,Cucumber章节中步骤定义中的代码也会起作用:

 @user = User.create!(:email => "email@email.com", :password => "password", :password_confirmation => "password") visit "login" fill_in("user_email", :with => @user.email) fill_in("user_password", :with => "password") click_button("Sign In") 

如果其他人有类似的问题……

我处于类似的情况(从Authlogic迁移),并有这个完全相同的问题。 问题出在devise.rb初始化程序中。 默认情况下,它会将您的测试环境设置为在加密/解密密码期间仅使用1次拉伸。 老实说,我不知道是什么延伸,但是对于Devise使用旧的Authlogic加密密码,延伸必须是20.因为我试图在我的测试中签署一个最初由Authlogic加密密码的用户,设计也需要在测试中使用20个延伸。 我改变了如下配置:

 # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. - config.stretches = Rails.env.test? ? 1 : 20 + config.stretches = 20 

由于您使用的是ActionDispatch::IntegrationTest ,因此您可以包含Devise::Test::IntegrationHelpers模块并使用sign_in方法(您可以将用户传递给它):

 class UserFlowsTest < ActionDispatch::IntegrationTest include Devise::Test::IntegrationHelpers test "sign in to the site" do sign_in users(:one) end end