How do I log in a user with Devise for Rails controller/integration unit tests?

China☆狼群 提交于 2020-01-17 06:57:06

问题


All the other answers are wrong or out of date. I've tried several things. This is what I have:

require 'test_helper'

class DealsControllerTest < ActionDispatch::IntegrationTest
  include Devise::Test::IntegrationHelpers

  setup do
    @deal = deals(:one)
    @user = users(:one)
    # https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-(and-RSpec)
    #@request.env["devise.mapping"] = Devise.mappings[:one]
    #sign_in @user
    #log_in_as @user
    ApplicationController.allow_forgery_protection = false
    post user_session_path, params: {user: {email: @user.email, password: @user.password}}
    assert_select "p", "Invalid Email or password."
    assert_response :redirect   ############ line 16
    #assert_text "Invalid Email or password."
    assert_redirected_to root_url
  end

Failure: DealsControllerTest#test_should_destroy_deal [C:/Users/Chloe/workspace/fortuneempire/test/controllers/deals_controller_test.rb:16]: Expected response to be a <3XX: redirect>, but was a <200: OK>

Since it passes the "Invalid email/password" test, that means the user is NOT logging in!

I tried these answers:

How to sign in a user using Devise from a Rails console?

How to sign_in for Devise to Test Controller with Minitest

https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-(and-RSpec)

Rails: Capybara can't log in user with Devise fixture data


回答1:


This worked

require 'test_helper'

class DealsControllerTest < ActionDispatch::IntegrationTest
  include Warden::Test::Helpers

  setup do
    @deal = deals(:one)
    @user = users(:one)
    # https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara
    @user.confirmed_at = Time.now
    @user.save
    login_as(@user, :scope => :user)
  end

  teardown do
    Warden.test_reset! 
  end


来源:https://stackoverflow.com/questions/43993465/how-do-i-log-in-a-user-with-devise-for-rails-controller-integration-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!