如何重新规范 Rails 配置类及其从 yml 文件创建的数组

发布于 2024-12-17 15:03:56 字数 1031 浏览 0 评论 0原文

我想知道是否有人对如何通过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苏璃陌 2024-12-24 15:03:56

存根不能解决您的问题吗?您可以存根现有的类,例如

@my_conf = {:whatever_you_want => :goes_here}
MyModile::Application.config.stub(:my_file).and_return(@my_conf)

Does stubbing not solve your problem? You can stub on an existing Class eg

@my_conf = {:whatever_you_want => :goes_here}
MyModile::Application.config.stub(:my_file).and_return(@my_conf)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文