[英]How to access a controller constant in an rspec test under Rails 3
Using Rails 3.2 I have a controller in a subdirectory (eg /controllers/data_feeds/acme_feed_controller.rb) 使用Rails 3.2我在子目录中有一个控制器(例如/controllers/data_feeds/acme_feed_controller.rb)
This controller has some constants as below 该控制器有一些常数如下
class DataFeeds::AcmeFeedController < ApplicationController
MY_CONSTANT = "hi
def do_something do
...
end
end
In my rspec controller spec (which is in /spec/controllers/data_feeds/acme_feed_controller_spec.rb) I want to access that constant and below are two ways I've tried it (both commented out in the code below) 在我的rspec控制器规范(在/spec/controllers/data_feeds/acme_feed_controller_spec.rb中)我想访问该常量,以下是我尝试过的两种方法(两种方式都在下面的代码中注释掉)
describe AcmeFeedController do
if "tests something" do
#c = AcmeFeedController.MY_CONSTANT
#c = DataFeeds::AcmeFeedController.MY_CONSTANT
end
end
I'm clearly not understanding something about the scope in which the spec test is run. 我显然不了解规范测试的运行范围。 What do I need to do and equally important why (ie what's happening with the scopes).
我需要做什么,同样重要的原因(即范围内发生了什么)。
Thanks for your help. 谢谢你的帮助。
Constants cannot be referenced with dot syntax, so DataFeeds::AcmeFeedController.MY_CONSTANT
would never work in any context. 常量不能用点语法引用,因此
DataFeeds::AcmeFeedController.MY_CONSTANT
永远不会在任何上下文中工作。 You need to use ::
to reference constants: DataFeeds::AcmeFeedController::MY_CONSTANT
. 您需要使用
::
来引用常量: DataFeeds::AcmeFeedController::MY_CONSTANT
。
Note that is a ruby issue and has nothing to do with RSpec. 请注意,这是一个红宝石问题,与RSpec无关。 When you face an issue like this, I recommend you figure out how to do it with plain ruby (eg in IRB) before worrying about how it works in RSpec (usually it will be the same, anyway).
当你遇到这样的问题时,我建议你弄清楚如何用纯红宝石(例如在IRB中)做这件事,然后再担心它在RSpec中是如何工作的(通常它会是相同的,无论如何)。
If you want to know how constants work in ruby, I commend you watch this talk that explains them in detail. 如果你想知道常量如何在ruby中工作,我建议你观看这个详细解释它们的讲话 。
Also, you can do this without repeating controller class name spaces. 此外,您可以执行此操作而无需重复控制器类名称空间。
describe AcmeFeedController do
if "tests something" do
c = controller.class.const_get('MY_CONSTANT')
end
end
This kind of trick may not be approved in application codes, but in tests it may be. 这种技巧可能不会在应用程序代码中得到批准,但在测试中可能会被批准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.