Starkers Starkers - 1 year ago 70
Ruby Question

What is Shoulda's route matcher for?

According to the shoulda page,

ActionController Matchers

- route tests your routes.

And I'm just not sure what it's used for. Especially in an isolated controller unit spec. Why is this in a controller spec? What's the relevance? Shouldn't this simply be in its own routes spec? And yet on the shoulda page this matcher is listed as an ActionController Matcher...

Or is ActionController in charge of routes so uses this matcher?

If I should be using this matcher in my controller specs, could I have an example to show how should I go about using this?

Answer Source

Why is shoulda-matchers' route matcher an ActionController matcher?

shoulda-matchers' route matcher is an ActionController matcher simply because its subject can be a controller. You can specify :controller yourself, in which case the subject doesn't matter:

describe 'Routing' do
  it { should route(:get, '/posts/1').to(controller: :posts, action: show, id: 1) }

or you can let it infer :controller for you:

describe PostsController do
  it { should route(:get, '/posts/1').to(action: show, id: 1) }

In the latter case, all route does with the subject (PostsController) is call .controller_name on it. But it uses the controller, so it's an ActionController matcher.

Is route for controller specs or routing specs?

Routing is a completely separate layer of Rails from controllers, so RSpec has separate controller and routing specs, and that's how I write them. But I do use shoulda-matchers, and I like to not have to type controller:, so I make the subjects of my routing specs controllers as in the second example above.

If you write your routing specs that way the subjects of your controller and routing specs are the same, so you might find it convenient to put your routing examples in your controller spec files. It would make it easier to keep your controller and routing specs in sync as you add or remove controller actions. I wouldn't argue against that. I would keep in mind, though, that the controller isn't really the subject of the routing specs; it's just saving you typing.

The shoulda-matchers rdoc suggests both possibilities.