Search code examples
ruby-on-railsrubyrspecrspec-rails

How to Stub functions with .try method in RSPEC


Doing RSPEC test....

Given I have:

ShopifyAPI::Product.all(:params => {:page => 1, :limit => 10, published_status: 'published', fields: 'id,handle'})

Then, I can stub it by:

allow(ShopifyAPI::Product).to receive(:all)
    .with(params: {page: 1, limit: 10, published_status: 'published', fields: 'id,handle'})
    .and_return( test_data )

BUT having trouble with .try(:first).try(:handle) method as below:

ShopifyAPI::Product.all(:params => {:page => 1, :limit => 10, published_status: 'published', fields: 'id,handle'}).try(:first).try(:handle)

CODE:

# MODEL
def test_product_handle
  ShopifyAPI::Product.all(:params => {:page => 1, :limit => 10, published_status: 'published', fields: 'id,handle'}).try(:first).try(:handle)
end


# CONTROLLER
def test
  @test_product_handle = @test.test_product_handle
end

# RSPEC HELPER
def test_product_handles
  [{id: 536491098170, handle: "awesome-sneakers"}, {id: 536491032634, handle: "cool-kicks"}]
end

# RSPEC

it "assigns value" do
  data = to_recursive_ostruct(test_product_handles.try(:first)).try(:handle) 
  # above returns "awesome-sneakers"

  allow(ShopifyAPI::Product).to receive(:all)
    .with(params: {page: 1, limit: 10, published_status: 'published', fields: 'id,handle'})
    .and_return( data )


  get :test

  expect(assigns(:test_product_handle)).to eq(data) # FAILED
  # BUT assigns(:test_product_handle) returns nil
end

Anything needs to adjust/add in my code above for stubbing it.

Thanks in advance.


Solution

  • Try this:

    data = test_product_handles.map { |hash| to_recursive_ostruct(hash) }
    # => Array of OpenStruct objects
    
    allow(ShopifyAPI::Product).to receive(:all).with(params: { page: 1, limit: 10, published_status: 'published', fields: 'id,handle' }) { data }