17

Controller code:

class BooksController < ApplicationController
  def index
    @books = Book.all
    respond_to do |format|
      format.html do
        render 'index', :layout => 'topgun'
      end
    end
  end
end

How should I test this in the spec?

require 'spec_helper'

describe BooksController do
  describe "GET index" do
    it "renders the topgun layout" do
      get :index
      # ???
    end
  end
end

I checked this related post, but my response object doesn't appear to have a layout attribute/method.

Community
  • 1
  • 1
Steven
  • 17,796
  • 13
  • 66
  • 118

2 Answers2

24

You may find the "Testing Controllers with RSpec" RailsCast and the official rspec-rails documentation helpful.

Looking at the code for assert_template (which is just what render_template calls), it looks like you should be able to do

response.should render_template("index")
response.should render_template(:layout => "topgun")

though I'm not entirely sure that will work.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • 1
    I'm not seeing the :layout option in the official docs/source for `assert_template` http://rails.rubyonrails.org/classes/ActionController/Assertions/ResponseAssertions.html#M000365 – raidfive Feb 14 '11 at 17:52
  • If you view the source for it there's a case `if options.key?(:layout)`. But now that I look at it a little closer, the `:partial` key might also have to be declared for it to check if there's a layout key. Also, you appear to be looking at the old rails docs, I was looking at the docs for 3.0 which are on http://api.rubyonrails.org – Andrew Marshall Feb 14 '11 at 17:56
  • We must be looking at different code/pages :) The one I linked has no :layout key. Are they out of date? – raidfive Feb 14 '11 at 18:01
  • 1
    Yea I think the one you were looking at is for 2.3, 3.0 docs are at http://api.rubyonrails.org/. The layout key is still hidden in the source code in the documentation and not a part of the examples, unfortunately. – Andrew Marshall Feb 14 '11 at 18:07
  • 1
    FYI, I wasn't able to test that the layout **is not** rendered by the controller. `expect(response).to render_template(layout: nil)` always passed no matter what the controller action did. RSpec 2.13.0, Rails 3.2.13. – Alex Fortuna Mar 28 '14 at 19:55
  • @dadooda Does `render_template(layout: false)` (i.e. false instead of nil) work instead? – Isaac Betesh Feb 05 '16 at 19:46
1

For RSpec 3:

expect(response).to render_template(:new)   # wraps assert_template

https://relishapp.com/rspec/rspec-rails/v/3-7/docs/controller-specs

Mugur 'Bud' Chirica
  • 4,246
  • 1
  • 31
  • 34