简体   繁体   中英

rails Devise authenticated routes in integration test

I want to test every route in an application, and learned I should do that in an integration test: Where to test routes in ruby on rails

However I'm getting the following error:

NoMethodError: undefined method `authenticate?' for nil:NilClass
/usr/local/Cellar/ruby/1.9.3-p194/lib/ruby/gems/1.9.1/gems/devise-2.1.2/lib/devise/rails/routes.rb:286:in `block in authenticated'

It's well-mentioned online that you can't use Devise::TestHelpers in integration testing -- Devise Google Group , Devise Github page


How can I test routes like the following?

# config/routes.rb

devise_for :users

authenticated :user do
  root to: 'static#home'
end

root to: 'static#landing'

I am running test unit tests with $ rake test:integration

Devise::TestHelpers work by putting things directly into your session. When running integration tests with Capybara, you don't have access to the server-side session. You just have access to the browser.

In our application, our integration tests use helper methods like this, that interact with Devise through the user interface:

def authenticate(user, password = nil)
  password ||= FactoryGirl.attributes_for(:user)[:password]
  visit new_user_session_path
  fill_in 'email', with: user.email
  fill_in 'password', with: password
  click_on 'Login'
  expect(current_path).to eq welcome_path
end

Integration tests are important for your application work flow. They can tell about your URL definition more clearly.

Check the post by nicholaides , that explains the cause of this error and the solution in Authenticated routes.

Still the problem is:

Devise has its own methods and you can't use Devise::TestHelpers in ruby. So how can you test? Well you need to include the Devise::TestHelpers somehow.

Well, if you're using RSpec, you can put the following inside a file named spec/support/devise.rb :

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

This is specified here .

But wait.......... Again, you can run into this same issue with Test::Unit .

Then?

So, you just need to add the devise test helpers to test/test_helper.rb .

class ActiveSupport::TestCase
  include Devise::TestHelpers
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM