测试rails helper呈现部分

时间:2013-06-21 13:19:40

标签: ruby-on-rails ruby rspec

鉴于以下帮助方法,我将如何使用rspec

正确测试此方法
  def datatable(rows = [], headers = [])
    render 'shared/datatable', { :rows => rows, :headers => headers }
  end

  def table(headers = [], data = [])
    render 'shared/table', headers: headers, data: data
  end

我尝试过以下操作,但收到错误:can't convert nil into String

describe 'datatable' do
  it 'renders the datatable partial' do
    rows = []
    headers = []
    helper.should_receive('render').with(any_args)
    datatable(rows, headers)
  end
end

Rspec输出

Failures:

  1) ApplicationHelper datatable renders the datatable partial
     Failure/Error: datatable(rows, headers)
     TypeError:
       can't convert nil into String
     # ./app/helpers/application_helper.rb:26:in `datatable'
     # ./spec/helpers/application_helper_spec.rb:45:in `block (3 levels) in <top (required)>'

./应用程序/助手/ application_helper.rb:26

render 'shared/datatable', { :rows => rows, :headers => headers }

视图/共享/ _datatable.html.haml

= table headers, rows

视图/共享/ _table.html.haml

%table.table.dataTable
  %thead
    %tr
      - headers.each do |header|
        %th= header
  %tbody
    - data.each do |columns|
      %tr
        - columns.each do |column|
          %td= column

4 个答案:

答案 0 :(得分:8)

如果您只想测试帮助者使用正确的参数调用正确的部分,您可以执行以下操作:

describe ApplicationHelper do

  let(:helpers) { ApplicationController.helpers }

  it 'renders the datatable partial' do
    rows    = double('rows')
    headers = double('headers')

    helper.should_receive(:render).with('shared/datatable', headers: headers, rows: rows)

    helper.datatable(rows, headers)
  end

end

请注意,这不会调用部分代码中的实际代码。

答案 1 :(得分:1)

should_receive的参数应该是符号而不是字符串。至少我没有看到在doc(https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations

中使用字符串

所以,而不是

helper.should_receive('render').with(any_args)

使用此

helper.should_receive(:render).with(any_args)

不确定这是否可以解决问题,但至少这是一个错误,可能导致您的错误消息。

答案 2 :(得分:1)

尝试:

describe 'datatable' do
  it 'renders the datatable partial' do
    rows = []
    headers = []
    helper.should_receive(:render).with(any_args)
    helper.datatable(rows, headers)
  end
end

帮助程序规范文档解释了这一点: https://www.relishapp.com/rspec/rspec-rails/v/2-0/docs/helper-specs/helper-spec

错误信息非常混乱,我不确定原因。

答案 3 :(得分:0)

这里有转换问题

  

无法将nil转换为String

你将2个空数组作为参数传递给函数,但是ruby中的空数组不是nil,那么render的参数应该是一个字符串,不确定但是尝试将测试中的参数转换为字符串,如下所示:

datatable(rows.to_s, headers.to_s)
相关问题