【问题标题】:In RSpec, how can I mock a method called with a constant argument?在 RSpec 中,如何模拟使用常量参数调用的方法?
【发布时间】:2016-03-16 22:05:48
【问题描述】:

我正在创建一个 gem,它在使用它的任何应用程序中都有一个常量(在运行生成器之后),但该常量在 gem 本身中不存在。我在 gem 中遇到 RSpec 问题,没有跳过调用常量的代码部分。下面是一个简单的例子。

class Foo
  def self.do_something
    Bar.send(FakeConstant.name)  #Bar.send is a valid class and method
  end
end

foo_spec.rb

it 'does something'
  expect(Bar).to receive(send).and_return('skipped!')
  Foo.do_something
end

rspec 输出

NameError: uninitialized constant FakeConstant

我想编写测试,让它完全跳过Bar.send 调用,这样它就永远不会知道其中有一个坏常量。确实没有解决此问题的好方法。

【问题讨论】:

  • I'm creating a gem that will have a constant in whatever app it is being used in (after a generator is run), but that constant doesn't exist in the gem itself - 这不是最好的主意。这里的用例是什么?通过配置在常量中提供对象会更好。

标签: ruby rspec rspec-mocks


【解决方案1】:

RSpec 的stub_const 方法允许你存根一个常量:

it 'does something'
  stub_const(FakeConstant, double(name: "Fakey McFakerson"))
  expect(Bar).to receive(send).and_return('skipped!')
  Foo.do_something
end

更多:https://www.relishapp.com/rspec/rspec-mocks/docs/mutating-constants/stub-defined-constant

也就是说,我同意 BroiSatse 的观点,如果提供一种更动态的方法将这些信息放入您的代码中,这样可以在测试中以更少的技巧进行操作,这可能会更好。

【讨论】:

    猜你喜欢
    • 2013-09-11
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-03
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多