jeudi 25 mai 2017

How to test session constrained routes with rspec routing specs?

I have such code in my routes.rb:

Rails.application.routes.draw do
  authorized     = ->(request) { request.session[:user_id].present? }
  not_authorized = ->(request) { request.session[:user_id].blank? }

  constraints authorized do
    resources :users
  end

  constraints not_authorized do
    get 'login' => 'auth#login_page'
    post 'login' => 'auth#create_session'

    get '*unmatched_route', to: 'auth#login_page'
    root 'auth#login_page'
  end
end

And I have such users_routing_spec.rb file:

require "rails_helper"

RSpec.describe UsersController, type: :routing do
  describe "routing" do
    it "routes to #index" do
      expect(:get => "/users").to route_to("users#index")
    end
  end
end

This test fails as it routes to 'auth#login_page' because there is no user_id in session. How can I call auth#create_session in advance to the expectation? There is no request or @request object and I also can't make a manual request to 'auth#create_session'

Aucun commentaire:

Enregistrer un commentaire