做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
任何东西都需要调整/添加上面的代码来存根。
提前致谢。
试试这个:
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 }