17th April, 2020 Output

Controller or Request Specs?

Overview

“For new Rails apps: we don’t recommend adding the rails-controller-testing gem to your application. The official recommendation of the Rails team and the RSpec core team is to write request specs instead.”

Request Specs

Request specs provide a thin wrapper around Rails' integration tests and are designed to drive behavior through the full stack, including routing (provided by Rails) and without stubbing (that's up to you).

With request specs, you can:

  • specify a single request

  • specify multiple requests across multiple controllers

  • specify multiple requests across multiple sessions

Example

require "rails_helper"

RSpec.describe "Widget management", :type => :request do

  it "creates a Widget" do

    headers = { "ACCEPT" => "application/json" }

    post "/widgets", :params => { :widget => {:name => "My Widget"} }, :headers => headers

    expect(response.content_type).to eq("application/json; charset=utf-8")

    expect(response).to have_http_status(:created)

  end

end

Controller Spec

A controller spec is more like a unit test for controllers since controllers are just Ruby classes like any other. You provide the input that each controller method expects and verify the output you want out the other end.

It allows you to simulate a single Http request in each example, and then

specify expected outcomes such as:

  • rendered templates

  • redirects

  • instance variables assigned in the controller to be shared with the view

  • cookies sent back with the response

Example

require "rails_helper"

RSpec.describe TeamsController do

  describe "GET index" do

    it "assigns @teams" do

      team = Team.create

      get: index

      expect(assigns(:teams)).to eq([team])

    end

    it "renders the index template" do

      get :index

      expect(response).to render_template("index")

    end

  end

end

Reference

Relish

Previous
Previous

Learning Outcomes - 20th April

Next
Next

Learning Outcomes - 15th April