RSpec - 模拟一个类方法

Chr*_*mer 13 ruby rspec ruby-on-rails mocking

我正在尝试用rspec模拟一个类方法:

LIB/db.rb

class Db
  def self.list(options)
    Db::Payload.list(options)
  end
end

LIB /分贝/ payload.rb

class Db::Payload
  def self.list(options={})
  end
end

在我的规范中,我正在尝试设置期望Db :: Payload.list将在我调用Db.list时被调用:

require 'db/payload'

describe Db do
  before(:each) do
    @options = {}
    Db::Payload.should_receive(:list).with(@options)
  end

  it 'should build the LIST payload' do
    Db.list(@options)
  end
end

问题是我总是收到以下错误:

undefined method `should_receive' for Db::Payload:Class

任何帮助理解这个错误将是非常感谢:-)

Rob*_*her 13

spec_helper.rb应该有这样的事情:

Spec::Runner.configure do |config|
  # == Mock Framework
  #
  # RSpec uses its own mocking framework by default. If you prefer to
  # use mocha, flexmock or RR, uncomment the appropriate line:
  #
  # config.mock_with :mocha
  # config.mock_with :flexmock
  # config.mock_with :rr
end
Run Code Online (Sandbox Code Playgroud)

默认参数是config.mock_with :rspec启用该should_receive方法的参数.例如,如果您使用的是Mocha,那么等效的是expects,所以请确保使用正确的模拟框架.