How to mock an array in RSpec?

13,005

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 }
Share:
13,005
ShayDavidson
Author by

ShayDavidson

Web, mobile and game developer.

Updated on June 04, 2022

Comments

  • ShayDavidson
    ShayDavidson over 1 year

    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?