4

我有一个名为 get_books_from_amazon 的辅助方法,它执行 API 调用并返回一组书籍。我无法弄清楚如何在我的请求规范中将其存根。

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

我在规范中尝试了以下方法,但均无济于事:

# 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

关于问题是什么的任何想法?

4

2 回答 2

8

在这种情况下,肯迪克的反应是很好的建议。

我已经添加了这个,以防有人真的在寻找原始问题的答案:

ActionView::Base.any_instance.stub(:helper_method) { "substitute return value" } 
于 2013-04-25T16:52:13.597 回答
5

助手通常用于清理演示“逻辑”,所以我不会在助手方法中调用亚马逊 API 之类的东西。

相反,将该方法移至可以从控制器调用的普通旧 Ruby 类。一个例子可能是:

class AmazonBookRetriever
  def get_books_from_amazon
    #code here
  end
end

然后你的控制器可以调用它:

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

这应该使模拟更容易。您可以存根返回一个模拟,并验证它是否接收到#new消息。AmazonBookRetrieverget_books_from_amazon

于 2012-10-23T20:30:04.393 回答