Auxiliary buffer method for specifying a request in rails / rspec

I have a helper method get_books_from_amazon that makes an API call and returns an array of books. I can't figure out how to drown it out in my query specifications.

module BooksHelper def get_books_from_amazon(search_term) ... end end class StaticController < ApplicationController include BooksHelper def resources @books = get_books_from_amazon(search_term) end end 

I tried the following in my specification, each to no avail:

 # spec/requests/resource_pages_spec.rb ... describe "Navigation" do it "should do such and such" do BooksHelper.stub!(:get_books_from_amazon).and_return(book_array) StaticHelper.stub!(:get_books_from_amazon).and_return(book_array) ApplicationHelper.stub!(:get_books_from_amazon).and_return(book_array) StaticController.stub!(:get_books_from_amazon).and_return(book_array[0..4]) ApplicationController.stub!(:get_books_from_amazon).and_return(book_array[0..4]) request.stub!(:get_books_from_amazon).and_return(book_array) helper.stub!(:get_books_from_amazon).and_return(book_array) controller.stub!(:get_books_from_amazon).and_return(book_array) self.stub!(:get_books_from_amazon).and_return(book_array) stub!(:get_books_from_amazon).and_return(book_array) visit resources_path save_and_open_page end 

Any ideas on what the problem is?

+4
source share
2 answers

Helpers are usually used to clear the presentation logic, so I would not put something like calling the Amazon API in a helper method.

Instead, move this method to a plain old Ruby class that you can call from your controller. An example would be:

 class AmazonBookRetriever def get_books_from_amazon #code here end end 

Then your controller can call it:

 def resources @books = AmazonBookRetriever.new.get_books_from_amazon(params[:search_term]) end 

This should make the mockery much easier. You can drown out #new on AmazonBookRetriever to return the layout, and make sure it receives the get_books_from_amazon message.

+5
source

Kendick's answer is good advice in this situation.

I added this if someone is really looking for an answer to the original question:

 ActionView::Base.any_instance.stub(:helper_method) { "substitute return value" } 
+7
source

Source: https://habr.com/ru/post/1441620/


All Articles