如何存根 ShopifyAPI::Theme.all 请求 RSPEC

How to stub ShopifyAPI::Theme.all request in RSPEC

我正在进行 RSPEC 测试,需要对 return 静态哈希进行存根或伪造请求。

我有:

ShopifyAPI::Theme.all.select{|t| t.role == "main"}.first

我知道要存根 ShopifyAPI::Theme.all,

喜欢allow(ShopifyAPI::Theme).to receive(:all).and_return( test_main_theme )

而且我有辅助方法。

 def test_main_theme
  {
   "id": 2335539244,
   "name": "Debut",
   "created_at": "2017-12-22T18:13:24-05:00",
   "updated_at": "2018-04-11T20:16:17-04:00",
   "role": "main",
   "theme_store_id": 796,
   "previewable": true,
   "processing": false
 }
end

但是.select{|t| t.role == "main"}.first是另一种方式。

提前致谢。

你可以试试:

allow(ShopifyAPI::Theme).to receive_message_chain(:all, :select, :first)
  .and_return(test_main_theme)

https://relishapp.com/rspec/rspec-mocks/v/3-5/docs/working-with-legacy-code/message-chains