简体   繁体   中英

Rails controller tests with devise sign in unexpected behavior

I am trying to create a simple tests on my application with devise. I have a redirect set up if the user is not logged in, but even though I use sign_in before the test I still get redirected. When I manually test this, it works fine.

users.yml

george:
  name: George
  email: george@example.com
  encrypted_password: <%= Devise::Encryptor.digest User, '123456' %>

addresses.yml

georges_home:
  title: Home
  receiver: George
  street: '132 Mitchell St SW'
  country: 'US'
  city: 'Atlanta'
  postal_code: '30303'
  phone: '+1 404-524-5665'
  state: 'Georgia'
  user: george

addresses_controller.rb

class AddressesController < ApplicationController
  before_action :login_needed

  def index
    @addresses = Address.where(user_id: @current_user.id)
  end

  private
  def login_needed
    if !user_signed_in?
      redirect_to new_user_session_path, alert: 'Please log in.'
    end
  end
end

addresses_controller_test.rb

require 'test_helper'

class AddressesControllerTest < ActionController::TestCase
  include Devise::TestHelpers

  setup do
    sign_in users(:george)
    @address = addresses(:georges_home)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:addresses)
  end
end

I found a piece of code that was dealing with fixtures of a User model with devise and the confirmable option. So my users' fixture should look like this:

users.yml

george:
  name: George
  email: george@example.com
  encrypted_password: <%= Devise::Encryptor.digest User, '123456' %>
  confirmed_at: <%= Date.today %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM