我在应用程序配置中定义了一个选项。我要测试的类(class)是在 gem 中定义的(不是我写的)。我想重新开课:
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 测试此代码:
# 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
如何在运行重新打开类的代码之前 stub 应用程序配置值。
最佳答案
哇,这已经存在很长时间了,但就我而言,我所做的是:
allow(Rails.configuration.your_config)
.to receive(:[])
.with(:your_key)
.and_return('your desired return')
规范传递和配置值正确 stub 。 =)
现在,另一件事是关于您的实现,我认为如果您从
run
定义两个方法和内部会更好或者你决定执行的事情。像这样的东西: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
希望这可以帮助。
编辑:哦,是的,我的错,我的回答基于此 one .
关于ruby-on-rails - 重新打开类时,RSpec : stubbing Rails. application.config 值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794443/