Max*_*vak 10 ruby-on-rails rspec3
我在应用程序配置中定义了一个选项.我要测试的类是在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
Run Code Online (Sandbox Code Playgroud)
我想使用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
Run Code Online (Sandbox Code Playgroud)
如何在运行重新打开类的代码之前存根应用程序配置值.
哇,这已经在这里待了很长时间,但就我而言,我所做的是:
allow(Rails.configuration.your_config)
.to receive(:[])
.with(:your_key)
.and_return('your desired return')
Run Code Online (Sandbox Code Playgroud)
规范传递和配置值正确存根.=)
现在,另一件事是关于你的实现,我认为如果你定义了两个方法和内部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
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
编辑:哦,是的,是我不好,我根据我对这个回答一个.