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 \
      "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>
Peter
  • 719
  • 1
  • 8
  • 19

1 Answers1

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.

DMH
  • 2,529
  • 3
  • 24
  • 35
  • 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 ' – Peter Dec 05 '16 at 14:27
  • 1
    @Peter do you have `confirmable` on the user model? – DMH Dec 05 '16 at 14:29
  • yes in models/user.rb I have confirmable: devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable – Peter Dec 05 '16 at 14:32
  • 1
    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. – DMH Dec 05 '16 at 14:38
  • ok thank you. Where should I put this confirmed_at: Time.now ? login_as(@heiko).confirmed_at: Time.now does not work – Peter Dec 05 '16 at 15:48
  • Ah I put it with @heiko.confirmed_at: Time.now. Great! Thanks – Peter Dec 05 '16 at 16:06