Umang Raghuvanshi
Umang Raghuvanshi

Reputation: 1258

RSpec: Testing concern which accesses params and request headers

I have this controller concern which accesses URL parameters and request headers.

module Authentication
  extend ActiveSupport::Concern
  # This concern has all authentication related functionality.
  # This should be extended into ApplicationController
  def current_user
    # Returns a user from a request header containing a session token or nil
    # or a URL parameter containing the same
    token = request.headers[:token] || params[:token]
    session = Session.find_by_token(token)
    session.user if session
  end

  def authenticated?
    # Is the user authenticated?
    # This makes no assumptions regarding that the user is privileged enough to do something
    return true if current_user
  end
end

I'm unsure of how to test this in RSpec. How do I do this?

Upvotes: 2

Views: 974

Answers (1)

Rajarshi Das
Rajarshi Das

Reputation: 12330

You can try shared example

# spec/support/authentication.rb
shared_examples "authentication" do
   # Your tests here
   let(:token) { "RandomString" }
   let(:user) {create(:user)}
   let(:session) {create(:session, token: token, user_id: user.id)}

   describe "#authenticated?" do
     it "should be authenticated" do
         session.user.should eq(user)
     end 
   end 
end


# spec/lib/authentication_spec.rb
module TestAuths
  class Authenticate
    include Authentication
  end
end

describe Authentication do

  context "inclusion of the module" do
    subject(:with_auth) { TestAuths::Authenticate.new }

    it_behaves_like "authentication"
  end

end

Upvotes: 1

Related Questions