Skip to content

Instantly share code, notes, and snippets.

@waterlink
Created March 16, 2014 15:19
Show Gist options
  • Save waterlink/9584734 to your computer and use it in GitHub Desktop.
Save waterlink/9584734 to your computer and use it in GitHub Desktop.
Rspec Devise helper with support for routing :authenticated and :unauthenticated tests
# spec/support/devise.rb
module Devise::RoutingTestHelpers
attr_accessor :request
def initialize(*args)
@request ||= Hashie::Mash.new env: {}
super(*args)
end
def request
@request ||= Hashie::Mash.new env: {}
end
def setup_controller(controller=subject)
request.env['action_controller.instance'] = @controller = controller
end
def sign_in!
NilClass.any_instance.stubs(:authenticate?).returns(true)
end
def sign_out!
NilClass.any_instance.unstub(:authenticate?)
NilClass.any_instance.stubs(:authenticate?).returns(false)
end
end
RSpec.configure do |config|
config.include Devise::TestHelpers, type: :controller
config.include Devise::RoutingTestHelpers, type: :routing
config.include Devise::TestHelpers, type: :routing
config.before(:each, type: :routing) do
setup_controller
sign_out!
end
end
# spec/routing/home_controller_spec.rb
require 'spec_helper'
describe HomeController do
describe 'root path' do
context 'when signed out' do
it 'routes to #landing' do
expect(get: '/').to route_to controller: 'home', action: 'landing'
end
end
context 'when signed in' do
before { sign_in! }
it 'routes to #index' do
expect(get: '/').to route_to controller: 'home', action: 'index'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment