[rspec-users] Stubbing return arguments

David Chelimsky
Sun, 16 May 2010 23:10:00 -0000

On May 15, 2010, at 2:56 AM, rhydiant wrote:

> I''m writting a code example for the following method:
>
>    def upload(email_address, product_data)
>      errors = []
>      user = resolve_user_from(email_address)
>      product_file_name = ProductFileHandler.persist(user,
> product_data, errors)
>      if errors.blank?
>        # ... do some stuff
>      else
>        # ... do some other stuff
>      end
>    end
>
> ProductFileHandler.persist will add any errors it encounters to the
> errors array I pass in. In my test of upload, I want to stub that
> error array with different values. After much googling and RSpec doc
> searching I can''t find a way to stub arguments like that? Is this
> possible with RSpec?

Assuming your goal is to test the different branches of the "if
errors.blank?" conditional, you could do something like this:

ProductFileHandler.stub(:persist) do |_,_,errors|
  # add stuff to errors here
  # return a reasonable value for product_file_name here
end

When the ProductFileHandler class receives the persist message, it will now
invoke this block with the three arguments it receives (user, product_data,
errors). Make sense?

This is pretty invasive but, given the current design, probably the simplest way
to go. If you want something less invasive, you probably need to change the
design.

HTH,
David