rails / rspec中请求规范的存根辅助方法

时间:2012-10-23 18:19:29

标签: ruby-on-rails-3 rspec mocking helper stub

我有一个名为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

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

2 个答案:

答案 0 :(得分:7)

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

我已添加此内容,以防有人真正寻找原始问题的答案:

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

答案 1 :(得分: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上存根AmazonBookRetriever以返回模拟,并验证它是否收到get_books_from_amazon消息。