简体   繁体   English

Application Helper Spec,测试控制器特定的输出?

[英]Application Helper Spec, test controller-specific output?

I'm a little unsure as to how to write a test for a helper method which has output that is based on the given controller and action that are requested. 我有点不确定如何编写一个辅助方法的测试,该方法的输出基于给定的控制器和请求的操作。

Given the following helper method in my application helper... 在我的应用程序帮助器中给出以下帮助器方法...

module ApplicationHelper
  def body_id
    [ controller.controller_name, controller.action_name ].join("_")
  end
end

... how would you write an application_helper_spec that tests this method? ...你会怎么写一个测试这个方法的application_helper_spec

Assign or mock the controller object. 分配或模拟控制器对象。 That will give you something to test against. 这会给你一些测试的东西。 (RSpec includes a very good mocking/stubbing library.) (RSpec包含一个非常好的模拟/存根库。)

rspec-rails has some built sugar for testing helpers as @marnen-laibow-koser mentioned. 正如@ marnen-laibow-koser所提到的,rspec-rails有一些用于测试助手的内置糖。 But I sometimes like to write very lightweight tests for my helpers that don't have to load in my whole rails environment. 但我有时喜欢为我的助手编写非常轻量级的测试,这些测试不必在我的整个rails环境中加载。 This way the tests can run in less than a second as opposed to the multiple seconds it takes to load the rails environment. 这样,测试可以在不到一秒的时间内运行,而不是加载rails环境所需的多秒。

Here is an example: 这是一个例子:

require 'spec_helper_lite'
require_relative '../../app/helpers/application_helper'

describe ApplicationHelper do
  let(:helper) do
    class Helper
      include ApplicationHelper
    end
    Helper.new
  end

  it "formats an elapsed time as a number of minutes and seconds" do
    helper.elapsed_as_min_sec(90).should == "1min 30sec"
  end
end

And my spec_helper_lite.rb file just looks like this: 我的spec_helper_lite.rb文件看起来像这样:

require 'rspec'
require 'rspec/autorun'

RSpec.configure do |config|
  config.order = "random"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM