Question

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 SessionsController 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.

Was it helpful?

Solution

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

  1. "get" is the correct http verb
  2. 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top