Mock Rails 4应用程序配置自定义值

时间:2017-01-06 21:51:14

标签: ruby-on-rails ruby rspec config ruby-on-rails-4.2

在Rails :: Application中,我使用...

添加自定义配置
allow(Rails.application.config.x).to recieve(:cache_config).and_return({})

在我的测试中,我想看看使用它的代码的行为取决于在cache.yml中如何定义配置。要在我的rspec测试中设置各种条件,我想做一些像......

#<Rails::Application::Configuration::Custom ... > does not implement: cache_config

但这不起作用。它出现错误

allow(Rails.application.config.x).to receive(:method_missing).with(:cache_config).and_return({})

3 个答案:

答案 0 :(得分:1)

经过多次挖掘和测试后,我想出了这个。

简答:

Map

除了......之外,本声明中的所有内容都必须准确无误。

  • :cache_config 替换为自定义配置密钥的名称
  • 使用您要为密钥设置的模拟值替换 and_return({})中的 {}

更长的回答:

如果你想深入研究为什么会这样,因为它一点也不明显,请查看代码......

答案 1 :(得分:0)

万一这对使用Mocha的人有帮助,我最终在帮助器中完成了

Rails.application.config.x.stubs(:my_config).returns(true)
yield
Rails.application.config.x.unstub(:my_config)

上面的method_missing技巧由于某些原因(猜测与实现存根的方式有关)而无效,并失败,并显示有关Configuration::Custom类未响应{的错误消息{1}}首次被其他配置引用。

答案 2 :(得分:0)

添加到上面的答案,如果你想存根嵌套配置,那么你必须确保你是 allow - 将配置中的倒数第二部分设置为 {{1} },因此:

receive(:method_missing)

以上代码存根 allow(Rails.application.config.x.foo.bar).to receive(:method_missing).with(:foobar).and_return(:baz) 配置以返回 Rails.application.config.x.foo.bar.foobar