RSpec: stubbing Rails.application.config value does not work when re-opening classes?

I have an option defined in the application configuration. My class that I want to test is defined in a gem (not written by me). I want to open the class again:

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 

I want to test this code with 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 lock the configuration value of an application before running code that reopens the class.

+7
ruby-on-rails rspec3
source share
1 answer

Wow, it has been here a long time, but in my case I did this:

 allow(Rails.configuration.your_config) .to receive(:[]) .with(:your_key) .and_return('your desired return') 

Passing and configuration values ​​are shaded correctly. =)

Now, one more thing about your implementation, I think it would be better if you defined both methods internally from run or something that you decided to execute. Something like that:

 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 

Hope this helps.

Edit: Oh yes, my bad, I based my answer on this one .

+4
source share

All Articles