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

1

14

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.

Fledgling answered 7/11, 2014 at 5:5 Comment(0)
A
13

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.

Anceline answered 12/2, 2016 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.