3

Im trying to define some controller macros for Rspec. Im using rails 3 and have my macros defined in spec/support/macros/controller_macros.rb, that file looks like this:

module ControllerMacros
    def self.login_admin
        #code
    end
end

in my spec helper I have:

config.include(ControllerMacros, :type => :controller)

So in my controller spec i just call login_admin in my admin tests but when ever i use the method i get

undefined local variable or method `login_admin' for #<Class:0xb6de4854> (NameError)

At first I assumed that controller_macros.rb wasn't being included but when I added a "puts" to the file but that showed the file was at least being executed.

I can't see anything wrong with my setup and copying the login_admin method into the describe block works fine so im not sure whats wrong with it.

Arcath
  • 4,331
  • 9
  • 39
  • 71
  • 1
    I'm not an expert on this but I think it's to do with the scoping ( self. ) of the method as its defined at class level. You may have to include it or extend it with base.included or base.extended, or maybe remove the self. – scaney Nov 19 '10 at 22:01
  • sorry self.included or self.extended – scaney Nov 19 '10 at 22:07

3 Answers3

10

Maybe I am late to that, but for new comers.

Here is a good examples of using macros:

http://osmose.6spot.com.br/2011/01/rails-resource-routing-spec-w-rspec/

when you include a module it's methods are visible inside examples.

But when you extend the module, it's methods are only visible outside examples.

It gives you ways to compose your macros for each situation.

feroult
  • 493
  • 5
  • 12
2

Try

ControllerMacros.login_admin

or remove self from the method definition.

zetetic
  • 47,184
  • 10
  • 111
  • 119
  • That does work but isnt the way it should really be done with rspec – Arcath Nov 19 '10 at 22:23
  • Sorry, I don't understand your comment. If you're defining a macro, you want to include it in many different examples, no? So there's no need to define a class method using `self`. Or did you mean something else? – zetetic Nov 19 '10 at 23:04
1

One line answer: Remove self from the method definition

Why? The methods of included modules are available in RSpec examples

The login_admin method defined in ControllerMacros will be available in your RSpec example as login_admin

To Be Specific:

Rewrite spec/support/macros/controller_macros.rb as

module ControllerMacros
    def login_admin
        #code
    end
end

Then tell Rspec to include the Macros

config.include(ControllerMacros, :type => :controller)

just__matt
  • 484
  • 6
  • 15