3

I am trying to mock an array in RSpec (in the app it's a return object from an external API), yet I don't know how.

I tried mocking it like this:

item = double("item")
item.stub(:[]) { :return_value }

which works, but then I'll get :return_value for each value in the array.

Is there another way?

1
  • 1
    i know a solution is to wrap the return object from the API in a wrapper and then mock it instead, but I'm trying to avoid it. Commented Jan 31, 2012 at 9:16

1 Answer 1

11

I think you don't need to generate test doubles for array, they will add unnecessary complication to the code of your tests. You can just create fake array and use it later:

items = [:return_value1, :return_value2]

In case if you need to stub method and return different results for first and subsequent calls, you can do this:

obj.stub(:method).and_return('1', '2')

In this case obj.method will return '1' when it is called for the first time and return '2' for all subsequent calls.

Also, as far as you use block for stub, you can dynamically calculate return value in this block. But this is considered to be not very good practice because idiomatically stubs should return static data.

obj.stub(:method) { Time.now }
Sign up to request clarification or add additional context in comments.

1 Comment

duh, didn't think about the easiest way of just creating an array. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.