Skip to content

Instantly share code, notes, and snippets.

@astjohn
Created November 1, 2012 18:59
Show Gist options
  • Save astjohn/3995730 to your computer and use it in GitHub Desktop.
Save astjohn/3995730 to your computer and use it in GitHub Desktop.
Rspec Setup for Controller Testing With Devise
# /spec/support/authentication.rb
# sign in methods to use in a before block
# you will then have access to the corresponding account variable such as '@user'
# or '@admin' throughout your test suite
# sign in a user
def sign_in_user(user=nil)
sign_out_all
@user = user || FactoryGirl.create(:user_w_trip)
sign_in @user
end
# sign in an admin
def sign_in_super_admin(admin=nil)
sign_out_all
@admin = admin || FactoryGirl.create(:super_admin)
sign_in @admin
end
def sign_in_content_admin(admin=nil)
sign_out_all
@content_admin = admin || FactoryGirl.create(:content_admin)
sign_in @content_admin
end
def sign_in_employee(employee=nil)
@employee = employee || FactoryGirl.create(:employee)
sign_in @employee
end
def sign_out_all
[@user, @admin, @employee].each do |obj|
sign_out obj if obj
end
end
# /spec/controllers/whatever_controller_spec.rb
require 'spec_helper'
describe Management::CountriesController do
let(:country) {mock_model(Country).as_null_object}
before(:all) do
sign_in_super_admin
end
describe "GET index" do
# Even though we can test this kind of thing through direct
# tests on ability.rb, I like to double down to make sure
context "regular user" do
before do
sign_in_user # this will sign out the admin
end
it "can not access" do
get :index
response.should redirect_to new_admin_session_path
end
end
# this test (and others) will have the admin as the currently
# logged in individual and you could have access by @admin
it "assigns all countries as @countries" do
Country.stub(:accessible_by) {[country]}
get :index
assigns(:countries).should eq([country])
end
# etc...
end
end
# /spec/support/devise.rb
RSpec.configure do |config|
config.include Devise::TestHelpers, :type => :controller
end
# /spec/factories/users.rb
FactoryGirl.define do
# confirmed user
factory :user do
name "Joe Blow"
email { FactoryGirl.generate(:email) }
confirmation_token nil
confirmed_at 1.day.ago
confirmation_sent_at 2.days.ago
unconfirmed_email nil
encrypted_password '$2a$10$/2wRkxh6dssddsGE5HyzPCcasd/BLHe8KAwewewe5e1ys5K5pWh$TvEzciqG'
password 'password'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment