I have a helper method called get_books_from_amazon that does an API call and returns an array of books. I can’t figure out how to stub it out in my request specs.
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 have tried the following in my spec, 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?
Helpers are typically used to clean up presentation “logic”, so I wouldn’t put something like a call to Amazon’s API in a helper method.
Instead, move that method to a plain old Ruby class which you can call from your controller.
An example might be:
Then your controller can call it:
This should make mocking a lot easier. You can stub
#newon theAmazonBookRetrieverto return a mock, and verify that it receives theget_books_from_amazonmessage.