集成测试登录的问题,环境是 rails 5.0.0.rc1 , devise 4.1.0
# intergation/users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with valid information" do
post user_session_path, session: { email: @user.email, password: 'password' }
assert_redirected_to @user
follow_redirect!
assert_select "a[href=?]", user_session_path, count: 0
end
...
# users.yml
michael:
username: Michael
email: [email protected]
encrypted_password: <%= User.new.send(:password_digest, "password") %>
admin: true
Failure:
UsersLoginTest#test_login_with_valid_information
Expected response to be a <3XX: redirect>, but was a <200: OK>
以上,浏览器手动测试都正确的,但测试就过不了!
第二个问题,上面的 users_login_test.rb 替换 devise sign_in 方法
# intergation/users_login_test.rb
require 'test_helper'
class UsersLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with valid information" do
sign_in :user, @user
assert_redirected_to @user
follow_redirect!
assert_select "a[href=?]", user_session_path, count: 0
end
...
test_helper.rb 有正确引入
# test_helper.rb
class ActionController::TestCase
include Devise::TestHelpers
end
会遇到没有 sign_in 方法错误!
NoMethodError: undefined method `sign_in'
抓狂!