2011-02-12 83 views
4

我有一個Rails 3助手,它根據params和request.headers返回代碼。我試圖嘲笑他們,但沒有成功。我的最新嘗試:rspec2:助手的假params和request.headers

require 'spec_helper' 

describe ApplicationHelper, "#banner" do 
    before do 
    @b728 = Factory :banner, :code => '<div style="width: 728px">:(clickref)</div>', :width => 728, :height => 90 
    @b160 = Factory :banner, :code => '<div style="width: 160px">:(clickref)</div>', :width => 160, :height => 600 

    Factory :ad_sense_channel, :key => "country", :value => nil, :ad_sense_id => 1 
    Factory :ad_sense_channel, :key => "country", :value => "de", :ad_sense_id => 2 
    # More ad_sense_channel factories here... 
    end 

    it "should return b728 for 728x90, left position and DictionariesController, German language and a guest and a German IP" do 
    helper.stub(:params) { {:controller => "dictionaries", :action => "index"} } 

    helper.stub(:request) do 
     request = double('request') 
     request.stub(:headers) { {"Accept-Language" => "de-DE, kr"} } 
     request 
    end 

    @detected_location = DetectedLocation.new("193.99.144.80") 
    banner(728, 90, "left").should eq('<div style="width: 728px">11+2+21+31+41</div>') 
    end 
end 

我仍然引發了一個異常:

NameError: 
     undefined local variable or method `params' for # 
    # ./app/helpers/application_helper.rb:7:in `banner'

解決方案:由於探究性,我的規格現在讀起來就像這樣:


controller.params = {:controller => "dictionaries", :action => "index"} 
controller.request.stub(:headers) { {"Accept-Language" => "de-DE, kr"} } 

@detected_location = DetectedLocation.new("193.99.144.80") 
helper.banner(728, 90, "left").should eq('11+2+21+31+41') 
+0

你能展現十足規格? – zetetic 2011-02-12 23:01:30

+0

@zetetic:我更新了代碼。 – iGEL 2011-02-12 23:19:57

回答

4

嘗試改變bannerhelper.banner

您會注意到,當使用方法名稱本身時背景是:

self.class # => RSpec::Core::ExampleGroup::Nested_1 

但從helper調用時,它的:

self.class # => ActionView::Base 

helper中的RSpec ::導軌:: HelperExampleGroup定義,這樣處理:

# Returns an instance of ActionView::Base with the helper being specified 
# mixed in, along with any of the built-in rails helpers. 
def helper 
    _view.tap do |v| 
    v.extend(ApplicationHelper) if defined?(ApplicationHelper) 
    v.assign(view_assigns) 
    end 
end