使用draper装饰器的rspec测试视图

时间:2012-03-13 09:41:13

标签: ruby-on-rails view rspec draper

我尝试使用Rspec测试我的视图。在我看来,我有一个由Draper生成的Decorator。这个装饰器由decent_exposure gem公开。

我创建了我的rspec测试:

require 'spec_helper'

describe "boats/show.html.slim" do

  let(:boat_decorate) { BoatDecorator.new(get_boat) }
  let(:search) { Search.new }

  before do
    view.stub(:boat_decorate) { boat_decorate }
    view.stub(:search) { search }
    render :template => 'boats/show.html.slim'
  end 

  it 'should see titlte' do
    rendered.should have_selector(:h1, :content => boat_decorate.title)
  end                                                                                                                                                                                
end

在我的助手存根中,我生成了Draper Decorator。在这个装饰器中,我有方法调用一些帮助器link_to

class BoatDecorator < ApplicationDecorator

  decorates :boat

  def region_link
    h.link_to region_name, '#', :title => region_name                                                                                                                                
  end

end

但如果我启动此测试,则会出现错误:

  1) boats/show.html.slim should see titlte
     Failure/Error: render :template => 'boats/show.html.slim'
     ActionView::Template::Error:
       undefined method `link_to' for nil:NilClass

我不希望我的装饰工具发出所有助手调用。那我该怎么办?

2 个答案:

答案 0 :(得分:6)

我们需要像Decorator规范那样添加设置:ApplicationController.new.set_current_view_context

require 'spec_helper'

describe "boats/show.html.slim" do

  let(:boat_decorate) { BoatDecorator.new(get_boat) }
  let(:search) { Search.new }

  before do
    ApplicationController.new.set_current_view_context
    view.stub(:boat_decorate) { boat_decorate }
    view.stub(:search) { search }
    render :template => 'boats/show.html.slim'
  end 

  it 'should see titlte' do
    rendered.should have_selector(:h1, :content => boat_decorate.title)
  end                                                                                                                                                                                
end

答案 1 :(得分:0)

另一种方法可能是使用rspec和capybara隔离测试装饰器类。 Here是显示使用此方法的示例代码。