【问题标题】:RSpec: stubbing Rails.application.config value doesn't work when reopening classes?RSpec:重新打开类时存根 Rails.application.config 值不起作用?
【发布时间】:2014-11-07 05:05:28
【问题描述】:

我在应用程序配置中定义了一个选项。我要测试的课程是在 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

我想使用 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

如何在运行重新打开类的代码之前存根应用程序配置值。

【问题讨论】:

    标签: ruby-on-rails rspec3


    【解决方案1】:

    哇,这已经在这里很久了,但就我而言,我所做的是:

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

    规范传递和配置值存根正确。 =)

    现在,另一件事是关于您的实现,我认为如果您从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
    

    希望这会有所帮助。

    编辑:哦,是的,我的错,我的回答是基于这个one

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多