Search code examples
rspecrspec-rails

Rspec: Rendering partials


I'm a little new to Rspec, this is probably an easy question to answer.

I am getting this error when trying to run a test:

Failure/Error: expect(view).to render_template(:partial => "_ad_column", :count => 2)                                                                                expecting _ad_column to be rendered 2 time(s) but rendered 0 time(s)                                                                                             # ./spec/views/requests_spec.rb:5:in `block (2 levels) in <top (required)>'

This is my test file:

require 'rails_helper'

RSpec.describe "requests/index", :type => :view do
  it "renders _ad_column" do
    expect(view).to render_template(:partial => "_ad_column", :count => 2)
  end
end

Essentially I have a partial that is rendered twice on every page, it's set in application.html.erb, I'm trying to make sure it shows up during the test. What am I doing wrong here? Thanks!

EDIT:

This is the view page I am testing (application.html.erb):

<!DOCTYPE html>
<html>
  <head>
    <title>Spellhub</title>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <div class="masthead">
      <%= render 'layouts/header' %>
      <!--<h5 class="muted">POC Application</h5>-->
    </div>
    <hr>

    <!-- required parent element for sticky ad-columns -->
    <div class="container-fluid">
      <!-- left column -->
      <%= render 'shared/ad_column', direction: 'left' %>

      <!-- page content goes here -->
      <div class="col-xs-8">
        <!-- for page flash alerts / to do -->
        <%= render 'layouts/messages' %>

        <%= yield %>
      </div>

      <!-- right column -->
      <%= render 'shared/ad_column', direction: 'right' %>
    </div>
  </body>
</html>

Solution

  • While the partial file name is _ad_column, the assertion will just be ad_column.

    EDIT:

    Since your partial is located in shared, you may need to assert on shared/ad_column.

    EDIT 2:

    I was incorrect, you should be asserting on the partial shared/_ad_column.

    What I think you are missing is the actual getting and displaying of the view.

    Does this work?

    it "renders _ad_column" do
      get "/" # Assuming this is the page you are trying to get.
      expect(response).to render_template(:partial => "shared/_ad_column", :count => 2)
    end
    

    EDIT 3: Try including render_views before your it block.