Reputation: 465
I use the latest oauth-plugin with Rails 3.1. I want to test my OAuth2 API controllers with rspec tests. After trying a bunch of things to authorize my request I simply want to stub the oauthenticate filter to get rid of any authentication issues. But I still get a 401 Unauthorized . Why??
users_controller.rb:
class UsersController
oauthenticate
def update
<do something>
end
end
users_controller_spec.rb:
describe UsersController do
describe "POST 'update'" do
before :each do
controller.stub!(:oauthenticate).and_return true
end
it "should be a successful request" do
post :update, { "user_id" => "some id" }
response.should be_ok
end
end
Expected ActionController::TestResponse to have a response code of 200, but got 401.
Rspec testing for oauth provider doesn't help. With cucumber test everything works fine when setting a valid access token Authorization header.
Upvotes: 0
Views: 3257
Reputation: 53
Similar to Peter's answer, except a bit nicer because it will only stub the method in the context of this spec:
before :each do
OAuth::Controllers::ApplicationControllerMethods::Filter.
any_instance.stub(:filter).and_return(true)
end
Upvotes: 2
Reputation: 431
your stubbing approach didn't work because oauthenticate is called as soon as the class is loaded, so by the time you stub is the before filter had already been set on the controller.
I found a way around this by redefining the underlying filter method, as follows:
before :each do
OAuth::Controllers::ApplicationControllerMethods::Filter.class_eval do
def filter(controller)
return true
end
end
end
I found this cleaner than having to create oauth tokens and headers, though of course it doesn't test your authentication anymore.
Upvotes: 1
Reputation: 465
OK I still don't know why oauthenticate becomes not stubbed, but I figured out, how to make a authenticated OAuth2 request in RSpec tests. You have to set oauth.strategies and token parameters of the request object:
def prepare_authenticated_access_token_request
# Create consumer application
@client_application = Factory.create(:client_application)
# Create a user who authorized the consumer
@resource_owner = Factory.create(:user)
# Create a valid, authorized access token
token = Oauth2Token.create :user => @resource_owner, :client_application => @client_application
# Configure the request object so that it is recognized as a OAuth2 request
request.env["oauth.strategies"] = [:oauth20_token, :token]
request.env["oauth.token"] = token
end
Upvotes: 2