在 Rspec 中添加控制器宏
我正在尝试为 Rspec 定义一些控制器宏。我使用rails 3并在spec/support/macros/controller_macros.rb中定义了我的宏,该文件如下所示:
module ControllerMacros
def self.login_admin
#code
end
end
在我的规范助手中我有:
config.include(ControllerMacros, :type => :controller)
所以在我的控制器规范中我只是在我的管理测试中调用login_admin,但是每当我使用我得到的方法
undefined local variable or method `login_admin' for #<Class:0xb6de4854> (NameError)
起初我假设不包含controller_macros.rb,但是当我向文件添加“puts”时,但这表明该文件至少正在执行。
我看不出我的设置有任何问题,并将 login_admin 方法复制到描述块中工作正常,所以我不确定它有什么问题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许我来晚了,但对于新来者来说。
以下是使用宏的一个很好的示例:
http://osmose。 6spot.com.br/2011/01/rails-resource-routing-spec-w-rspec/
当您包含模块时,它的方法在示例中可见。
但是当您扩展模块时,它的方法仅在示例之外可见。
它为您提供了针对每种情况编写宏的方法。
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.
尝试
从方法定义中删除
self
。Try
or remove
self
from the method definition.一行答案: 从方法定义中删除 self
为什么? 包含的模块的方法在 RSpec 示例中可用
login_admin
方法定义在ControllerMacros
将在您的 RSpec 示例中以login_admin
的形式提供具体说明:
重写
spec/support/macros/controller_macros.rb
然后告诉 Rspec 包含宏
config.include(ControllerMacros, :type => :controller)
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 inControllerMacros
will be available in your RSpec example aslogin_admin
To Be Specific:
Rewrite
spec/support/macros/controller_macros.rb
asThen tell Rspec to include the Macros
config.include(ControllerMacros, :type => :controller)