ruby-on-rails - 重新打开类时,RSpec : stubbing Rails. application.config 值不起作用?

标签 ruby-on-rails rspec3

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

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

最佳答案

哇,这已经存在很长时间了,但就我而言,我所做的是:

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

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

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

关于ruby-on-rails - 重新打开类时,RSpec : stubbing Rails. application.config 值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26794443/

相关文章:

css - Bootstrap 导航栏居中链接并右对齐其他链接

ruby-on-rails - 无法使表单 date_select 隐藏在 rails 中

ruby-on-rails - 在 Rails 中测试 Rake : Multiple Error Raises Silenced In Test

ruby-on-rails - 如何添加我已使用 Carrierwave 上传的图像的缩略图版本

ruby-on-rails - Rails 4 belongs_to 在数组列中存储 id

ruby-on-rails - 如果设置了 graphQL 字段方法参数默认值,则使用 RSpec 进行测试

ruby - RSpec 参数匹配哈希数组

ruby-on-rails - RSpec中的 "be_true"和 "be true"有什么区别

actionmailer - Rails 4、RSpec 3.2 - 如何模拟 ActionMailer 的 Deliver_now 方法来引发异常

ruby-on-rails - 使用RSpec测试Rails辅助方法时,如何在params哈希中设置值?