Where should I put authenticated tests using Devise + RSpec?

I am new to Rails. We use Devise for user authentication and RSpec for testing the application (Rails 4).

I have a model Adminthat has access to some authenticated routes. Here is an excerpt from routes.rb:

devise_for :admins

authenticate :admin do
  get 'admin', to: 'admin#index'
end

It (obviously) works flawlessly: if I visit /admin, I get redirected to /admins/sign_in, and as soon as I log in (or if I'm already in a session), I have direct access to /admin.

Now, as I understand it, routes should be tested internally spec/routes/<controller_name>_routes_spec.rb. I like the idea of ​​testing routes (and that the right controller handles each route with the right action, etc.) independently.

We encounter the problem of testing routes when the indicated routes authenticated. Including

config.include Devise::TestHelpers[, type: :controller]

internally spec/spec_helper.rbstill does not allow the use of methods sign_in(or sign_[out|up]) inside route specifications.

What should we do? How should we test authenticated routes? It just seems wrong to me that non-authenticated routes are checked how spec/routes, while authenticated routes should be tested inside integration tests, manually filling out login forms with things similar to Capybara.

( note : I read this one , but that didn't help)

+3
source share
1 answer

, spec_helper. :

...

RSpec.configure do |config|
  config.include Devise::TestHelpers

...

end

def sign_in_user( user=nil )
  @user = FactoryGirl.build(:user)
  @user.skip_confirmation!
  @user.save!
  sign_in @user
end

, , ​​ , .

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
  config.include Devise::TestHelpers, type: :routing

...

end

, . :

"spec_helper"

RSpec.describe WidgetsController, :type => :controller do
  describe "routing" do

    before(:each) do 
      sign_in_user
    end

    it "routes to #index" do
      expect(:get => "/widgets").to route_to("widgets#index")
    end

    it "routes to #new" do
      expect(:get => "/widgets/new").to route_to("widgets#new")
    end

    it "routes to #show" do
      expect(:get => "/widgets/1").to route_to("widgets#show", :id => "1")
    end

    it "routes to #edit" do
      expect(:get => "/widgets/1/edit").to route_to("widgets#edit", :id => "1")
    end

    it "routes to #create" do
      expect(:post => "/widgets").to route_to("widgets#create")
    end

    it "routes to #update" do
      expect(:put => "/widgets/1").to route_to("widgets#update", :id => "1")
    end

    it "routes to #destroy" do
      expect(:delete => "/widgets/1").to route_to("widgets#destroy", :id => "1")
    end
  end
end
0

All Articles