biw
biw

Reputation: 3085

Test View Yield in RSpec

I have a view layout file that currently yields:

Layout.html.slim:

html
  header
    [content]
  = yield :page_content
  footer
    [content]

and then a template file that follows the same format.

template.html.slim:

- content_for :page_content
  #hello

I want to be able to test the content of the template without testing any content on the layout. I have found that if I create a rake layout file I can do the following in rspec:

describe "template.html.slim", type: :view do
  it "should render a div" do
    render template: 'template', layout: 'test_yielder'
    expect(rendered).to have_tag("#hello")
  end
end

where test_yielder is a one line file:

= yield :page_content

While this gets the job done, I was wondering if there was a cleaner way to test the content of template without needing to create an extra test_yielder file and only change how I call the render function?

Does a cleaner way exist?

Upvotes: 0

Views: 600

Answers (1)

mabe02
mabe02

Reputation: 2734

I usually test the output of a template when it is rendered by a controller.

Following your approach you can refer to view_spec.

View specs live in spec/views and render view templates in isolation.

# app/views/widgets/widget.html.erb
<h2><%= @widget.name %></h2>


# spec/views/widgets/widget.html.erb_spec.rb
require "spec_helper"

describe "rendering the widget template" do
  it "displays the widget" do
    assign(:widget, stub_model(Widget, name: "slicer"))

    render template: "widgets/widget.html.erb"
    rendered.should contain("slicer")
  end
end

This would work already without taking in consideration any layout. Eventually, you can specify render template: 'something', layout: false but is not really needed.

I would say that this is already a clean solution.

You can eventually add an helper module in your test suite if you repeat this action several time (see this answer)

if your template.html.slim is correct, your test should work as expected. (I found this pretty old issue on slim repo for reference)

Upvotes: 1

Related Questions