Pavel
Pavel

Reputation: 4410

How to test rendering a partial with RSpec

I want to test rendering a particular partial according to some conditions.

For example, in model show action view show.html.erb I have:

<% if condition1 %>
 <%=  render :partial => "partial1" %>
<% else %>
 <%=  render :partial => "partial1" %>
<% end %>

I tried:

response.should render_template("partial_name")

but it tells that it rendered "show" template

expecting <"partial1"> but rendering with <"model/show, layouts/application">

What I am doing wrong?

Upvotes: 52

Views: 30919

Answers (7)

Dende
Dende

Reputation: 584

You can also test, if your controller inferred required action.

require "spec_helper"

describe "model_name/new.html.erb" do
 it "infers the controller path" do
  expect(controller.request.path_parameters["action"]).to eq("new")
 end
end

The docs are here

Upvotes: 1

coorasse
coorasse

Reputation: 5528

Starting from Rails 5.1, this kind of test is discouraged and you should test the controller and the view as a whole.

Checking which partial is rendered by the controlled is part of the implementation details you shouldn't test.

Therefore I suggest you to write a request test and check that some relevant text of your partial is present in the response body.

get root_path
expect(CGI.unescape_html(response.body)).to include('Hello World')

Upvotes: 0

user2238766
user2238766

Reputation: 61

If using in rspec controllers

expect(response).to render_template(partial: 'home/_sector_performance')

Upvotes: 1

Diego D
Diego D

Reputation: 1776

If you are testing this inside a controller you should do something like this:

RSpec.describe Users::RegistrationsController, type: :controller do
  describe "GET #new" do
    render_views

    it "render customer partial" do
      get :new
      expect(response).to render_template :new
      expect(response).to render_template(partial: '_new_customer')
    end
  end
end

Note that we need render_views as reported into documentation.

And this is the line that will test if "_new_customer" partial is rendered:

expect(response).to render_template(partial: '_new_customer')

You need to provide the name of the partial with the initial underscore.

Also be careful because in your code the IF and the ELSE statements are rendering the same thing.

Upvotes: 7

Seb Wilgosz
Seb Wilgosz

Reputation: 1250

Latest rspec version suggest to use expect syntax rather than should:

expect(response).to render_template(partial: 'partial_name')

Upvotes: 34

auralbee
auralbee

Reputation: 8841

Instead of the above mentioned solution you could check alternatively, if the html that the partial renders is present. E.g.

response.body.should have_tag("div#foo")

Upvotes: -4

Rishav Rastogi
Rishav Rastogi

Reputation: 15492

Also try this

response.should render_template(:partial => 'partial_name')

Upvotes: 72

Related Questions