From 9ef4a0f0753f4c93353431669c41a5b89716dbbb Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Thu, 4 Feb 2021 11:12:02 -0600 Subject: [PATCH] Add Render The Response Body In Controller Specs a rails til --- README.md | 3 +- ...r-the-response-body-in-controller-specs.md | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 rails/render-the-response-body-in-controller-specs.md diff --git a/README.md b/README.md index f2fe493..34e155e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1033 TILs and counting..._ +_1034 TILs and counting..._ --- @@ -667,6 +667,7 @@ _1033 TILs and counting..._ - [Read-Only Models](rails/read-only-models.md) - [Remove The Default Value On A Column](rails/remove-the-default-value-on-a-column.md) - [Render An Alternative ActionMailer Template](rails/render-an-alternative-action-mailer-template.md) +- [Render The Response Body In Controller Specs](rails/render-the-response-body-in-controller-specs.md) - [Rescue From](rails/rescue-from.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) - [Rounding Numbers With Precision](rails/rounding-numbers-with-precision.md) diff --git a/rails/render-the-response-body-in-controller-specs.md b/rails/render-the-response-body-in-controller-specs.md new file mode 100644 index 0000000..f9caca2 --- /dev/null +++ b/rails/render-the-response-body-in-controller-specs.md @@ -0,0 +1,35 @@ +# Render The Response Body In Controller Specs + +Controller specs skip the rendering of views by default. If you want to inspect +some aspect of what is rendered in the HTML body of a response +(`response.body`), you can include the `render_views` directive in that spec. + +```ruby +require 'rails_helper' + +RSpec.describe DashboardController do + describe '#index' do + render_views + + context 'when there is a signed in user' do + it 'includes their email' do + user = User.create(email: 'user@example.com') + + sign_in(user) + + get :index + + expect(response.body).to include('user@example.com') + end + end + end +end +``` + +The `render_views` directive call can go at the top of a spec, and all views +for all tests will be rendered. Or you can place it in the nested contexts only +where it is needed. + +View rendering is skipped by default in an effort to keep tests speedy. To not +unnecessarily slow down your test suite, make sure to use it sparingly and only +in tests where you are actually inspecting `response.body`.