Last active
August 29, 2015 14:13
-
-
Save alyssais/00a9b834db160fe71866 to your computer and use it in GitHub Desktop.
Testing controller concerns in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is an example spec that uses the ControllerConcernHelper module | |
require "rails_helper" | |
describe Authentication, type: :controller_concern do | |
controller do | |
include AbstractController::Callbacks | |
before_action :authenticate | |
def test_action | |
render text: authenticated_device.id | |
end | |
end | |
context "when no authentication is supplied" do | |
it "responds with 401 Unauthorized" do | |
expect(request.get("/").status).to eq 401 | |
end | |
end | |
context "when correct authentication is supplied" do | |
let!(:secret) { SecureRandom.uuid } | |
let!(:device) { create(:device, secret: secret) } | |
let!(:response) { request.get("/", authenticate(device.id, secret)) } | |
it "responds with 200 OK" do | |
expect(response.status).to eq 200 | |
end | |
it "finds device ID" do | |
expect(response.body.chomp).to eq device.id | |
end | |
end | |
context "when incorrect authentication is supplied" do | |
it "responds with 401 Unauthorized" do | |
authentication = authenticate(SecureRandom.uuid, SecureRandom.uuid) | |
response = request.get("/", authentication) | |
expect(response.status).to eq 401 | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ControllerConcernHelper | |
module ClassMethods | |
def controller(&block) | |
before { controller(&block) } | |
end | |
end | |
def controller(&block) | |
@controller ||= begin | |
concern = described_class | |
Class.new(ActionController::Metal) do | |
include concern | |
end | |
end | |
@controller.class_eval(&block) if block | |
@controller | |
end | |
def app | |
@controller.action(:test_action) | |
end | |
def request | |
Rack::MockRequest.new(app) | |
end | |
end | |
RSpec.configure do |config| | |
config.include ControllerConcernHelper, type: :controller_concern | |
config.extend ControllerConcernHelper::ClassMethods, type: :controller_concern | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment