Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec: stubbing Rails.application.config value doesn't work when reopening classes?

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

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.

like image 868
Max Ivak Avatar asked Nov 07 '14 05:11

Max Ivak


1 Answers

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. =)

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

Hope this helps.

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

like image 183
leomilrib Avatar answered Sep 23 '22 19:09

leomilrib