Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test whether my controller rendered the right layout on Rails 3?

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.

like image 636
Steven Avatar asked Feb 14 '11 17:02

Steven


People also ask

How can you tell Rails to render without a layout *?

By default, if you use the :plain option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the layout: true option and use the . text. erb extension for the layout file.

How do I run a test in Rails?

2.7 The Rails Test Runner Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case. You can also run a particular test method from the test case by providing the -n or --name flag and the test's method name.

How do you test a method in Ruby?

Most methods can be tested by saying, “When I pass in argument X, I expect return value Y.” This one isn't so straightforward though. This is more like “When the user sees output X and then enters value V, expect subsequent output O.” Instead of accepting arguments, this method gets its value from user input.

What is unit test Rails?

The Tests − They are test applications that produce consistent result and prove that a Rails application does what it is expected to do. Tests are developed concurrently with the actual application. The Assertion − This is a one line of code that evaluates an object (or expression) for expected results.


2 Answers

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.

like image 172
Andrew Marshall Avatar answered Oct 08 '22 08:10

Andrew Marshall


For RSpec 3:

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

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

like image 23
Mugur 'Bud' Chirica Avatar answered Oct 08 '22 10:10

Mugur 'Bud' Chirica