Search code examples
ruby-on-railsdevise

How can I use the devise user_signed_in? method in an integration test?


When I have assert user_signed_in? in an integration test it says the method is undefined. Is there a way I can use this method in my testing? I am using rails 4 and the latest version of devise. Here is my test file:

require 'test_helper'

class UsersSignupTest < ActionDispatch::IntegrationTest

test "valid signup information" do
    get new_user_registration_path
    assert_difference 'User.count', 1 do
      post_via_redirect user_registration_path, 
                                     user: { first_name: "Example",
                                             last_name:  "User",
                                             email:      "[email protected]",
                                             password:              "password",
                                             password_confirmation: "password" }
    end
    assert_template 'activities/index'
    assert user_signed_in?
  end

Solution

  • The user_signed_in? method is included in Devise::Controllers::Helpers module which isn't available in your integration tests so you can't use it.

    You have the option of either mocking this method (which won't really meet your testing needs) or testing that a user is signed in by looking for page content that will only render when the user is signed in like Logout link for example or Signed in successfully message.

    For your controller tests you can use devise test helpers include Devise::TestHelpers which exposes a sign_in and sign_out methods for you, more on that in the Gem's home page https://github.com/plataformatec/devise