module ModelStubbingHelpers
  def stub_record(type, options = {})
    result = build(type, options)
    result.stubs(:id).returns(next_record_id)
    result.stubs(:new_record?).returns(false)
    result.stubs(:created_at).returns(Time.zone.now) if result.respond_to?(:created_at)
    result.stubs(:updated_at).returns(Time.zone.now) if result.respond_to?(:updated_at)
    result
  end

  def stub_edition(type, options = {})
    document = stub_record(:document)
    document.stubs(:to_param).returns(document.slug)
    stub_record(type, options.merge(document: document))
  end

  def next_record_id
    @next_id ||= 0
    @next_id += 1
  end
end

module ModelStubbingHelpers
  def stub_record(type, options = {})
    build_stubbed(type, options)
  end

  def stub_edition(type, options = {})
    document = stub_record(:document)
    document.stubs(:to_param).returns(document.slug)
    stub_record(type, options.merge(document: document))
  end

  def next_record_id
    @next_id ||= 0
    @next_id += 1
  end
end

Use FactoryGirl.build_stubbed instead of a hand-rolled solution.
Use FactoryGirl.build_stubbed instead of a hand-rolled solution.

`FactoryGirl.build_stubbed` takes care of all this (and more).

I had run into problems with the previous implementation where, because
the "stub record" was still an instance of the `ActiveRecord::Base`
subclass (albeit with lots of stubbed method), and because its
`#new_record?` method returned `true`, it was possible for a database
query to be initiated by something as simple as inspecting the record or
calling an association method.

This problem was compounded in the cases I saw, because Mocha tried to
report the unexpected invocation of `select` on the `ActiveRecord`
connection, but in doing so it also wanted to list the stubbed methods
on the record. The latter caused a recursive call to the record's
`#inspect` method and an eventual stack overflow error.
