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

1

5

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 \
      "[email protected]"    => 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>
Endoergic answered 5/12, 2016 at 12:55 Comment(0)
C
7

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.

Chronaxie answered 5/12, 2016 at 14:21 Comment(6)
if I add include_Warden::Test::Helpers and use login_as(@heiko) in should_get_new then this error appears: AppointmentsControllerTest#test_should_get_new: UncaughtThrowError: uncaught throw :warden test/controllers/appointments_controller_test.rb:26:in `block in <class:AppointmentsControllerTest>'Endoergic
@Endoergic do you have confirmable on the user model?Chronaxie
yes in models/user.rb I have confirmable: devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmableEndoergic
Ok so the issue is your user you created isnt confirmed hence the redirect. Try adding confirmed_at: Time.now to your creation of the user.Chronaxie
ok thank you. Where should I put this confirmed_at: Time.now ? login_as(@heiko).confirmed_at: Time.now does not workEndoergic
Ah I put it with @heiko.confirmed_at: Time.now. Great! ThanksEndoergic

© 2022 - 2024 — McMap. All rights reserved.