[rspec-users] Stubbing return arguments

David Chelimsky dchelimsky at gmail.com
Sun May 16 19:10:00 EDT 2010

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

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.


More information about the rspec-users mailing list