RSpec:重新打开类时存根 Rails.application.config 值不起作用? [英] RSpec: stubbing Rails.application.config value doesn't work when reopening classes?
问题描述
我在应用程序配置中定义了一个选项.我要测试的课程是在 gem 中定义的(不是我写的).我想重新开课:
I have an option defined in application config. My class I want to test is defined in a gem (not written by me). I want to reopen the class:
Myclass.class_eval do
if Rails.application.config.myoption=='value1'
# some code
def self.method1
end
else
# another code
def self.method2
end
end
end
我想使用 RSpec 3 测试此代码:
I want to test this code using RSpec 3:
# myclass_spec.rb
require "rails_helper"
RSpec.describe "My class" do
allow(Rails.application.config).to receive(:myoption).and_return('value1')
context 'in taxon' do
it 'something' do
expect(Myclass).to respond_to(:method1)
end
end
end
如何在运行重新打开类的代码之前存根应用程序配置值.
How to stub application config value before running the code which reopens a class.
推荐答案
哇,这已经存在很长时间了,但就我而言,我所做的是:
Wow, this have been here for a long time, but in my case what I did was:
allow(Rails.configuration.your_config)
.to receive(:[])
.with(:your_key)
.and_return('your desired return')
规范传递和配置值存根正确.=)
Specs passing and config values stubed correctly. =)
现在,另一件事是关于你的实现,我认为如果你从 run
或你决定执行的东西中定义两个方法和内部会更好.像这样:
Now, the other thing is about your implementation, I think it would be better if you defined both methods and inside from a run
or something you decided wich one to execute. Something like this:
class YourClass
extend self
def run
Rails.application.config[:your_option] == 'value' ? first_method : second_method
end
def first_method
# some code
end
def second_method
# another code
end
end
希望这会有所帮助.
哦,是的,我的错,我的回答基于这个一个.
Oh yeah, my bad, I based my answer on this one.
这篇关于RSpec:重新打开类时存根 Rails.application.config 值不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!