Take the 2-minute tour ×

I would like to create some especial stub methods stub_check and stub_chain_check that ensure the method exists.

For example:


describe PaymentsController do
  it "makes a payment" do
    # Ensure method exists, Payment.new.respond_to?(:pay)
    # the API of Payment can change and tests will pass
    raise "Stubbing wrong method Payment#pay method doesn't exists" unless Payment.new.respond_to?(:pay)
    Payment.any_instance.stub(pay: true) # We can stub method now
    # Code...

But I would like to to somwthing like Payment.stub_check(pay: true)

share|improve this question

1 Answer 1

You can create a helper on your spec_helper.rb file:

def stub_check(resource, method, value, message)
  raise message unless resource.new.respond_to?(method)
  resource.any_instance.stub(method => value)

and you call it with

stub_check(Payment, :pay, true, 'Stubbing wrong method Payment#pay method doesn't exists')

EDIT: if you want this to work like stub, you may need to modify mocka or the matchers your are using (I guess it's mocka because of the "any_instance" method)

share|improve this answer
I have thought about that one, and it's not a good Idea to use resourse.new.respond_to? method, it's better resource.method_defined? method, but I would like to do Payment.stub_check –  Boris Barroso Jan 21 '13 at 18:14

Your Answer


