Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test that rails helper renders a partial

Given the following helper method, how would I properly test this using 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

I've tried the following but I get the error: 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 Output

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

./app/helpers/application_helper.rb:26

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

views/shared/_datatable.html.haml

= table headers, rows

views/shared/_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
like image 381
Kyle Decot Avatar asked Dec 27 '22 01:12

Kyle Decot


2 Answers

if you just want to test that your helper calls the right partial with the correct parameters you can do the following:

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

note that this won't call the actual code in your partial.

like image 191
Linki Avatar answered Dec 30 '22 08:12

Linki


The argument of should_receive should be a symbol instead of string. At least I have not seen string is used in doc(https://www.relishapp.com/rspec/rspec-mocks/v/2-14/docs/message-expectations)

So, instead of

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

Use this

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

Not sure if this could solve the problem but at least this is an error which cause your error message probably.

like image 29
Billy Chan Avatar answered Dec 30 '22 07:12

Billy Chan