Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RSpec - mocking a class method

I'm trying to mock a class method with rspec:

lib/db.rb

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

lib/db/payload.rb

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

In my spec, I'm trying to setup the expectation Db::Payload.list will be called when I call 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

The problem is that I am always receiving the following error:

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

Any help understanding this error would be most appreciated :-)

like image 467
Chris Kilmer Avatar asked May 09 '10 13:05

Chris Kilmer


1 Answers

Your spec_helper.rb should have something like this:

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

The default argument is config.mock_with :rspec which enables the should_receive method. If you're using Mocha, for example, the equivalent is expects, so make sure you're using the right mocking framework.

like image 192
Robert Speicher Avatar answered Oct 18 '22 12:10

Robert Speicher