使用Rspec 2和Devise测试Rails 3中的助手

问题描述:

我的帮助程序代码看起来像这样(并且工作正常btw):

My helper code looks like this (and works fine btw):

module ProvidersHelper
  def call_to_review(provider)
    if user_signed_in? && review = Review.find_by_provider_id_and_user_id(provider.id, current_user.id)
      link_to "Edit Your Review", edit_provider_review_path(provider, review), :class => "call_to_review"
    else
      link_to "Review This Provider", new_provider_review_path(provider), :class => "call_to_review"
    end
  end
end

不幸的是运行测试时会产生以下错误:

Unfortunately, this produces the following error when I run my tests:

 undefined method `user_signed_in?' for #<ActionView::Base:0x00000106314640>
 # ./app/helpers/providers_helper.rb:3:in `call_to_review'

显然,当rspec运行测试时,我的帮助者中没有包含 Devise :: Controllers :: Helpers 。任何可能有助于这项工作的建议?

Clearly the Devise::Controllers::Helpers are not being included in my helpers when rspec is running the test. Any suggestions that might help this work?

编辑:为了提供更多的信息,我的spec_helper有这样的:

to provide a bit more information, my spec_helper does have this:

config.include Devise::TestHelpers, :type => :controller
config.include Devise::TestHelpers, :type => :view
config.include Devise::TestHelpers, :type => :helper

(可惜的是,我无法让它与一起工作: type => [:controller,:view,,helper]

(Sadly, I couldn't get it to work with :type => [:controller, :view, :helper])

无论如何,我相信这些行添加了 sign_in(scope,object)(和其他)测试助手进行测试。他们不会添加您在控制器/视图代码中实际利用的帮助器。

Anyway I believe that these lines add the sign_in(scope, object) (and other) test helpers to your tests. They don't add the helpers that you would actually leverage in your controller / view code.

我认为rspec的理念是尽可能全面地测试视图/帮助者/模型。所以在这种情况下,我会存储 user_signed_in?并返回 false true ,我的结果应该适当地改变。
这给你一个干净的隔离测试。

I think the philosophy of rspec is to test the view/helpers/models in total isolation as much as possible. So in this case, i would stub out the user_signed_in? and returns false or true and my results should change appropriately. This gives you a clean isolated test.