ruby-on-rails - rspec2:帮助者的假参数和 request.headers

标签 ruby-on-rails rspec helper rspec2

我有一个 Rails 3 助手,它根据参数和 request.headers 返回代码。我试图 mock 他们,但没有成功。我最近的尝试:

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

我仍然提出了一个异常(exception):
NameError:
       undefined local variable or method `params' for #
     # ./app/helpers/application_helper.rb:7:in `banner'

解决方案:感谢 zetetic,我的规范现在如下所示:

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

最佳答案

尝试更改 bannerhelper.banner
您会注意到,当单独使用方法名称时,上下文是:

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

但是当从 helper 调用电话时它的:
self.class # => ActionView::Base
helper在 RSpec::Rails::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

关于ruby-on-rails - rspec2:帮助者的假参数和 request.headers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4980665/

相关文章:

ruby-on-rails - Rails 条件获取(开发模式)仍然返回 "Not Modified"(`#fresh_when()` )

ruby-on-rails - 在 Ruby 中打开 .doc 文件

ruby-on-rails - 使用 RSpec 测试使用 CanCan 和 Devise 的 View

ruby-on-rails - 如何在cucumber中看到页面写入 "should not"?

ruby-on-rails-3 - Rails 3 - 如何在标签助手中自定义文本标签?

ruby-on-rails - Ruby on Rails - 在 html.erb 中使用助手

cakephp - CakePHP 中的自定义助手错误

ruby-on-rails - 测试邮箱 : last email is nil when sent through a background worker

ruby-on-rails - 来自 Michael Hartl 的 RoR 教程第 11 章关注用户的 Rspec 方法 'be_following'

ruby-on-rails - 在其他测试中重用 RSpec 测试