Created
March 16, 2015 17:24
-
-
Save nathanows/b7dde50423d6ceb822ab to your computer and use it in GitHub Desktop.
RSpec: Testing HTTP:Basic Authentication
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
## | |
## HTTP:Basic AUTHENTICATION | |
## This was based on blogger-advanced | |
## Continuing from the class we built this in... | |
## | |
# app/controllers/api/v1/articles_controller.rb | |
class Api::V1::ArticlesController < ApplicationController | |
#... | |
before_action :authenticate | |
#... | |
private | |
def authenticate | |
authenticate_or_request_with_http_basic("Please authenticateto use the API") do |email, password| | |
author = Author.find_by(email: email) | |
return true if author && author.authenticate(password) | |
head :unauthorized | |
end | |
end | |
# spec/support/auth_helper.rb | |
module AuthHelper | |
def http_login | |
email = '[email protected]' | |
password = 'password' | |
request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(email, password) | |
end | |
end | |
# spec/spec_helper.rb (or rails_helper.rb, whichever, but in the existing RSpec.configure block include the AuthHelper module) | |
RSpec.configure do |config| | |
config.include AuthHelper, :type => :controller | |
end | |
# Skipping the Factory girl setup steps (find them here http://www.rubydoc.info/gems/factory_girl/file/GETTING_STARTED.md) | |
# Summary: add 'factory_girl_rails' and 'database_cleaner' gems to your Gemfile | |
# From the link above, add in the code snippets from the 'Configure your test suite' and 'Linting factories' sections | |
# spec/factories.rb | |
FactoryGirl.define do | |
factory :author do | |
name "John Doe" | |
email "[email protected]" | |
password "password" | |
end | |
factory :article do | |
title "How to play cards" | |
body "It's pretty simple really..." | |
author | |
end | |
end | |
# controller spec (spec/controllers/app/v1) | |
require 'spec_helper' | |
RSpec.describe Api::V1::ArticlesController, :type => :controller do | |
describe "GET index" do | |
it "responds to json" do | |
create(:author) | |
create_list(:article, 2) | |
http_login #this is the method call from the AuthHelper module | |
get :index, format: 'json' | |
items = JSON.parse(response.body) | |
first_item = items.first | |
expect(response.status).to eq(200) | |
expect(items.count).to eq(1) | |
expect(first_item["title"]).to eq("How to play cards") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment