ruby-on-railsunit-testingdevisecancancan

controller test: <302: Found> redirect to <http://www.example.com/users/sign_in>


I have a problem with unit testing in ruby on rails (rails v. 5.001). I use devise and cancancan for authorization. The user needs to login in a test unit, but how can I implement this without redirecting to http://www.example.com/users/sign_in? Here is the code:

appointments_controller_test.rb

require 'test_helper'

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

  def sign_in(user)
    post user_session_path \
      "heiko@me.com"    => user.email,
      "hhdk#s0" => user.password
  end

  setup do
    @heikoAppointment = appointments(:appointment_heiko)
    @heiko = users(:user_heiko)
    sign_in(@heiko)
  end

  test "should get index" do
    get appointments_url
    assert_response :success
  end

  test "should get new" do
    sign_in(@heiko)
    get new_appointment_url
    assert_response :success
  end

And here is the Error I get when I run the test:

Error:
AppointmentsControllerTest#test_should_get_new [C:/Users/Clemens/meindorfladen/Server/test/controllers/appointments_controller_test.rb:33]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>

Solution

  • The issue is your user is not confirmed.

    You need to pass in

    confirmed_at = Time.now
    

    to the user you create. That will then stop you getting redirected.