Categories
Rails rspec Ruby

“You have to declare the controller name in controller specs”

For ages I’ve been getting an intermittent problem with RSpec, where occasionally I’d see the following error on a model spec:

You have to declare the controller name in controller specs. For example:
describe "The ExampleController" do
controller_name "example" #invokes the ExampleController
end

The problem seemed to depend on which order the specs were run in, and for rake it could be avoided by removing --loadby mtime --reverse from spec.opts. It was a real pain with autotest though, and today (my original plan of “wait for RSpec 1.1 and hope it goes away” having failed) I finally got round to looking into it properly.

It seemed that the error was being triggered by the rather unpleasant code I wrote a while ago to simplify testing of model validation. Digging into the RSpec source to see what was happening, I found that that error message only gets returned when (as you’d expect) you don’t declare the controller name in a controller spec (specifically in an instance of Spec::Rails::Example::ControllerExampleGroup). The code that decides what type of example group to create lives in Spec::DSL::BehaviourFactory, and according to its specs, there are two methods it uses to figure out what type of spec it’s looking at:

it "should return a ModelExampleGroup when given :type => :model" do
...
it "should return a ModelExampleGroup when given :spec_path => '/blah/spec/models/'" do
...
it "should return a ModelExampleGroup when given :spec_path => '\\blah\\spec\\models\\' (windows format)" do
...
it "should favor the :type over the :spec_path" do
...

I began to suspect that the problem was caused by the fact that my specify_attributes method wasn’t declared in a file in spec/models, so I thought I’d try specifying the type explicitly. So instead of this:

describe "#{label} with all attributes set" do

I changed it to this:

describe "#{label} with all attributes set", :type => 'model' do

Sure enough, it worked! Not sure whether anyone else is likely to see the same problem (unless they’re foolish enough to use my validation spec code), but hopefully if you do, a Google search will bring up this post and it might point you in the right direction.

One reply on ““You have to declare the controller name in controller specs””

Leave a Reply