[rspec-users] How to test a controller
sfeley at gmail.com
Fri Oct 17 02:28:30 EDT 2008
On Fri, Oct 17, 2008 at 1:35 AM, Mano ah <lists at ruby-forum.com> wrote:
> I want to test the controllers of an existing project. How can i do it.
> Actually when I use ruby script/spec rspec_scaffold modelname it
> creates a spec controller for that model and a controller inside the app
The really obvious (and probably unhelpful) answer would be, "Just
write the specs, dude."
Expanding on that: there's nothing magic about the specs generated by
the scaffold. I'm not even sure that they're great specs; they're
just one opinion on how to test the default, plain-vanilla Rails
actions. They'll stop passing the moment you change anything, and
then you'll have to understand what they're doing and fix them. (And
any non-trivial Rails app _will_ end up doing _something_ different
than what the default scaffold controllers do.)
I know in my case, I didn't understand the controller specs at all
until I wrote some by hand. And then I wrote some more by hand, and
understood them better. For a while I was using make_resourceful and
mock_resourceful... I stopped, and rewrote those by hand, because
there was too much magic and I couldn't follow what was going on. The
end result was more lines of code, but it was just as good as what the
plugins did and better-suited to my requirements, and I _understood_
it. That's worth more than the specs themselves are worth.
So ignore the scaffold stuff, unless you want to look back at it as a
reference example, and write some specs for the way your controller
currently behaves. Do some mock objects for your models...or don't,
as mocking too is just a matter of opinion. But test that the models
are at least being called to find the right objects. Write at least
one spec for the output of each controller action, making sure it
renders what you want it to, and then write more if you think you need
Keep doing this, and keep maintaining your specs the same way you'd
refactor the actual code, and eventually you'll start to Get It.
You'll feel good about your specs without having to ask anyone.
Eventually you'll look at the example code and go, "Man, I can do
better!" At that point, congratulations. You've cleared the level.
Proceed to Level 2 -- whatever that may be for your particular style.
Just don't stop learning things. If you stop, Donkey Kong keeps the
Hope this was helpful.
Steve Eley (sfeley at gmail.com)
ESCAPE POD - The Science Fiction Podcast Magazine
More information about the rspec-users