如何在 RSPEC 中使用 .try 方法存根函数

How to Stub functions with .try method in RSPEC

正在进行 RSPEC 测试....

鉴于我有:

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

然后,我可以通过以下方式存根:

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

但是 在使用 .try(:first).try(:handle) 方法时遇到问题,如下所示:

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

代码:

# 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

我上面的代码中的任何东西都需要 adjust/add 来存根。

提前致谢。

试试这个:

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 }