Skip to content

Instantly share code, notes, and snippets.

@dsandstrom
Last active December 12, 2020 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsandstrom/917a9b6fff195704dc90bef9f4574bb7 to your computer and use it in GitHub Desktop.
Save dsandstrom/917a9b6fff195704dc90bef9f4574bb7 to your computer and use it in GitHub Desktop.
View spec helper for CanCanCommunity/cancancan
# spec/support/authentication.rb
# Enable can? method in view specs for cancancan gem
#
# Example:
#
# ```
# let(:admin) { Fabricate(:user_admin) }
# before { enable_can(view, admin) }
# ```
module TestHelpers
module Authentication
# set the current_user
def enable_can(view, user)
without_partial_double_verification do
allow(view).to receive(:can?) do |action, record|
ability = Ability.new(user)
ability.can?(action, record)
end
allow(view).to receive(:current_user) { user }
end
end
# setup a guest user for devise
def enable_devise_user(view)
without_partial_double_verification do
allow(view).to receive(:resource) { User.new }
allow(view).to receive(:resource_class) { User }
allow(view).to receive(:resource_name) { :user }
allow(view).to receive(:devise_mapping) { Devise.mappings[:user] }
end
end
end
end
# spec/support/authorizaton.rb
module TestHelpers
module Authorization
def expect_to_be_unauthorized(response)
expect(response).to redirect_to(:unauthorized)
end
def enable_devise_user(controller, user = nil)
without_partial_double_verification do
@request.env['devise.mapping'] = Devise.mappings[:user]
allow(controller).to receive(:resource) { user } if user
end
end
end
end
# spec/rails_helper.rb
..
Dir[Rails.root.join('spec/support/**/*.rb')].sort.each { |f| require f }
RSpec.configure do |config|
..
config.include TestHelpers::Authentication, type: :view
config.include TestHelpers::Authorization, type: :controller
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment