RSpec - 模拟一个类方法

时间:2010-05-09 13:32:34

标签: ruby-on-rails ruby mocking rspec

我正在尝试用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

理解这个错误的任何帮助都将非常感激: - )

1 个答案:

答案 0 :(得分: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

默认参数为config.mock_with :rspec,它启用should_receive方法。例如,如果您使用的是Mocha,则等效值为expects,因此请确保使用正确的模拟框架。