Adding Controller Macros in Rspec

折月煮酒 提交于 2019-12-10 09:43:53

问题


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.


回答1:


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.




回答2:


Try

ControllerMacros.login_admin

or remove self from the method definition.




回答3:


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)



来源:https://stackoverflow.com/questions/4229756/adding-controller-macros-in-rspec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!