如何重新规范 Rails 配置类及其从 yml 文件创建的数组
我想知道是否有人对如何通过 MyModile::Application.config
方法调用 rspec(模拟)下面我的类中返回的 Rails Configuration 实例有任何建议?
我了解如何模拟在我的类中创建的对象,以便使用以下内容进行测试:
let(:my_class_mock) { double("MyClass").as_null_object }
MyClass.stub(:new).and_return my_class_mock
但应用程序不是在我的类中创建的。 我想模拟它是用 myfile 调用的并返回一个模拟数组,这样我就可以确保它读取正确的值,例如“url”
class ConfigReader
def initialize
my_conf = MyModile::Application.config.myfile
@url = my_conf["url"]
end
end
编辑: 我忘记了我已经创建了这样的初始化程序:
EXTERNAL_CONFIG_FILE_PATH = "#{::Rails.root.to_s}/config/myfile.yml" config_file_exists = FileTest.exists?(EXTERNAL_CONFIG_FILE_PATH)
case
when config_file_exists # if it does exist, load it
MyMobile::Application.config.myfile= YAML.load_file(EXTERNAL_CONFIG_FILE_PATH)[::Rails.env]
when !config_file_exists
raise "#{EXTERNAL_CONFIG_FILE_PATH} configuration file is missing"
end
我将尝试存根 YAML.load_file 以查看是否可以返回我自己的数组模拟。
I was wondering if anyone had any suggestions how to rspec (mock) the Rails Configuration instance returned in my class below by the MyModile::Application.config
method call?
I understand how to mock out objects that are created within my class to be tested using something like:
let(:my_class_mock) { double("MyClass").as_null_object }
MyClass.stub(:new).and_return my_class_mock
But Application is not created within my class.
I want to mock out that is it called with myfile and return a mocked array so I can ensure its reading the correct values e.g. "url"
class ConfigReader
def initialize
my_conf = MyModile::Application.config.myfile
@url = my_conf["url"]
end
end
Edit:
I forgot I had created an initializer like this:
EXTERNAL_CONFIG_FILE_PATH = "#{::Rails.root.to_s}/config/myfile.yml" config_file_exists = FileTest.exists?(EXTERNAL_CONFIG_FILE_PATH)
case
when config_file_exists # if it does exist, load it
MyMobile::Application.config.myfile= YAML.load_file(EXTERNAL_CONFIG_FILE_PATH)[::Rails.env]
when !config_file_exists
raise "#{EXTERNAL_CONFIG_FILE_PATH} configuration file is missing"
end
I will try and stub the YAML.load_file to see if I can return my own array mock.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
存根不能解决您的问题吗?您可以存根现有的类,例如
Does stubbing not solve your problem? You can stub on an existing Class eg