正在进行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
任何内容都需要调整/添加,以便存根。
谢谢。
答案 0 :(得分: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 }