I’m fond of mocking collaborators on controllers, to keep’em highly focused on their job when testing (which is forwarding incoming params, sending responses, etc).
The controller is generally the web app’s main integration point, where things are forwarded and global constants are directly referenced, such as classes.
When you mock or stub something on a controller, you usually have to work with global constants, like:
This kind of mocking has some potential problems, because it deals with global state. Weird errors may pop up if you try to parallelize your test suite, for example. There are other concerning problems as well.
Recently I’m experimenting with stubbing private methods, exceptionally on controllers. As long as your interfaces are simple, you don’t make a mess and you have some integration tests, it doesn’t feel that bad, I think. Something like:
# Controller private def build_post Post.new end # Test @controller.stub(:build_post).and_return(post)
Stubbing out the
build_post method makes the mentioned problem go away, because we are acting on an instance. We can also make getters / setters on the controller, but that alternative actually feels worse.
Do you guys have any thoughts on the matter?