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

天大地大妈咪最大 提交于 2019-12-09 09:23:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26794443/rspec-stubbing-rails-application-config-value-doesnt-work-when-reopening-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!