2015-12-26 66 views
1

我有訪問URL參數和請求標頭的這個控制器問題。RSpec:訪問參數和請求標題的測試問題

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 

我不確定如何在RSpec中測試它。我該怎麼做呢?

+0

爲什麼downvote,downvoter?你也可以在評論中提出建議。 –

回答

1

您可以嘗試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