What Does The View Test Do?
Learn about view testing functionalities, and how to make the view test pass.
View testing performance
In the following added view test, first, we create the given: data. We use let
to create the on-schedule project and task. The objects need to be in the database so that the Rails associations all work. But other choices might make the test faster, including creating projects and stubbing the on_schedule?
method or using FactoryBot.build_stubbed
to create real objects without saving them in the database.
require 'rails_helper'describe 'projects/index' dolet(:on_schedule) doProject.create!(due_date: 1.year.from_now,name: 'On Schedule')endlet(:behind_schedule) doProject.create!(due_date: 1.day.from_now,name: 'Behind Schedule')endlet(:completed_task) doTask.create!(completed_at: 1.day.ago,size: 1,project: on_schedule)endlet(:incomplete_task) doTask.create!(size: 1,project: behind_schedule)endit 'renders the index page with correct dom elements' doon_schedule.tasks << completed_taskbehind_schedule.tasks << incomplete_task@projects = [on_schedule, behind_schedule]renderwithin("#project_#{on_schedule.id}") doexpect(rendered).to have_selector('.on_Schedule')endexpect(rendered).to have_selector("#project_#{on_schedule.id} .on_schedule")expect(rendered).to have_selector("#project_#{behind_schedule.id} .behind_schedule")endend
View testing isolation
In the spec itself, we set the @projects
variable. We’re testing the view in isolation, so we don’t have a controller to set this up for us. We need to create the instance variables given to the view.
Local variables
Our “when” section is one line, render
, which tells RSpec to render the view. Which view? The one specified by the outermost describe
block. In this ...