Search code examples
ruby-on-railsrspec-railsshopify-app

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


I'm doing RSPEC testing and need to stub or make a fake request to return static hash.

I have:

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

I know to stub that ShopifyAPI::Theme.all,

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

And I have helper method.

 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

but having .select{|t| t.role == "main"}.first is another way.

Thanks in advance.


Solution

  • You can try:

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

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