mardi 2 août 2016

Rails controller tests with devise sign in unexpected behavior

I am trying to make 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

Aucun commentaire:

Enregistrer un commentaire