How do I unit test a controller method that is called via a custom route?
The relevant route is:
/auth/:provider/callback(.:format) {:controller=>"sessions", :action=>"create"}
On the spec for the Sessio开发者_开发百科nsController
I can't just use get :create
since that route doesn't exist. If I also use get /auth/facebook/callback/
it'll tell me that No route matches {:controller=>"sessions", :action=>"/auth/facebook/callback"}
.
It also seems like I can't just use controller.create
since #create
accesses some keys from the request
hash and it also redirects to another path, even if I set request.env['something'] in the spec file.
A functional test should test the function of each action (given a set of parameters)
Crucially, you should keep your functional tests decoupled from your routes. (else what's the point in the routing abstraction anyway)
In test::unit a functional test looks something like this
test "#{action_name} - does something" do
#{http_verb} :#{action_name}, :params => {:their => "values"}
assert_response :#{expected_response}
end
Note, we don't mention routing anywhere.
So a real example for your create
test "create - creates a session" do
get :create, :provider => "your provider"
assert_response :success
end
Rails will choke if it can't match a route to this request.
If this doesn't work I suggest you check two things
- "get" is the correct http verb
- there are no other required parameters in your route (I can see :provider is one)
If I'm doing anything wacky with routing, I normally add a separate test.
test "create - routing" do
assert_recognizes({
:controller => "sessions",
:action => "create",
:provider => "yourProvider"
}, "/auth/yourProvider/callback")
end
As long as this matches up with your action test all should be well.
精彩评论