" /> " /> "/>

What class to expect helper method calls on when called from a view?

1k Views Asked by At

I have a view, that calls a helper. In my rspec tests, I want to check that this helper is called with the appropriate attributes.

<div class="chart">
  <%= chart_tag(:pie, {css: 0.1, javascript: 0.3, ruby: 0.6}) %>
</div>

I don't want to test that chart_tag is rendering the correct HTML; it is a complex helper that sets all kinds of data- attributes; it sets highcharts params. This method itself is tested properly.

I want to test something like:

expect(TemplateClass::SomeHelper).to receive(:chart_tag).with(:pie)

I don't know where to set the expectations on: I don't know how cells renders things. It seems that it leverages rails' rendering stack, but that too is an unfamiliar area for me.

I am calling this through cells, so the generic rspec view does not apply here.

In cells, helpers are included with helper, which, as far as I can tell, is a rails method. But following that code, still does not tell me what is included in the view, through what proxy, class or module.

To illustrate part of the stack/code:

class AnalysisCell < Cell::Rails
  helper ChartHelper

  def chart(params)
    @type = params[:type] || :pie
    @dataset = params[:dataset] || {}
    render # Cells will now, magically, parse and process app/cells/analysis/chart.html.erb
  end
end

app/cells/analysis/chart.html.erb

<%= debugger %>
<%= chart_tag(:pie, {css: 0.1, javascript: 0.3, ruby: 0.6}) %>

app/helpers/chart_helper.rb

module ChartHelper
  def chart_tag(type, dataset)
  end
end

When falling into the debugger, I can inspect the state from within the erb:

self.class #=> #<Class:0x007f9eef0215a8>
self._helpers #=> NoMethodError Exception: undefined method `_helpers
self.methods.sort #=>
# [...
# :cell_for,
# :chart_tag,
# :check_box_tag,
# ...]
# self.method(:chart_tag).owner #=> ChartHelper

But the test fails with received: 0 times with any argument:

it 'renders a chart' do
  expect(ChartHelper).to receive(:chart_tag) #.with(:pie, {})
  render_cell(:analysis, :chart, type: :pie, dataset: {})
end

Any idea what to test the message-expectation on?

1

There are 1 best solutions below

1
LostHisMind On

In my view specs, I would typically write

expect(view).to receive(:chart_tag).with(:pie)