开发者

rspec2: Fake params and request.headers for helpers

I've got an Rails 3 helper, which returns code depending on the params and request.headers. I've tried to mock them, but didn't succeed. My latest try:

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">1开发者_StackOverflow中文版1+2+21+31+41</div>')
  end
end

I still raises an exception:

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

Solution: Thanks to zetetic, my spec now reads like this:


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')


Try changing banner to helper.banner

You'll note that when using the method name by itself the context is:

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

But when calling from helper it's:

self.class # => ActionView::Base

helper is defined in RSpec::Rails::HelperExampleGroup and does this:

# 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜