Cannon Moyer
Cannon Moyer

Reputation: 3164

Run controller tests with Devise

I'm trying to run a rake test using devise (using a user that's been created by database seeds)

Running rake test produces the following error:

Failure:
CustomersControllerTest#test_should_get_index [/home/ubuntu/workspace/test/controllers/customers_controller_test.rb:7]:
Expected response to be a <2XX: success>, but was a <302: Found> redirect to <http://www.example.com/users/sign_in>
Response body: <html><body>You are being <a href="http://www.example.com/users/sign_in">redirected</a>.</body></html>

My test looks like this:

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

It's a very simple test, but I don't know how to actually login to the site before performing the test.

Upvotes: 0

Views: 1747

Answers (1)

csexton
csexton

Reputation: 24793

To test actions that require an authenticated user you can use Devise's sign_in and sign_out helpers. These come from Devise::Test::ControllerHelpers on your test case or its parent class (or Devise::Test::IntegrationHelpers for Rails 5+):

class CustomersControllerTest < ActionController::TestCase
  include Devise::Test::ControllerHelpers # <-- Include helpers
  test "should get index" do
    sign_in User.create(...) # <-- Create and authenticate a user
    get customers_url
    assert_response :success
  end
end

See the controller tests section in the Devise README for details.

Upvotes: 3

Related Questions