我有这个控制器问题,它访问URL参数和请求标题。
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 :(得分: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