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

问题描述 投票:0回答:1

做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

任何东西都需要调整/添加上面的代码来存根。

提前致谢。

ruby-on-rails ruby rspec rspec-rails
1个回答
1
投票

试试这个:

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 }
© www.soinside.com 2019 - 2024. All rights reserved.