...

/

What Does The View Test Do?

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.

Press + to interact
require 'rails_helper'
describe 'projects/index' do
let(:on_schedule) do
Project.create!(
due_date: 1.year.from_now,
name: 'On Schedule'
)
end
let(:behind_schedule) do
Project.create!(
due_date: 1.day.from_now,
name: 'Behind Schedule'
)
end
let(:completed_task) do
Task.create!(
completed_at: 1.day.ago,
size: 1,
project: on_schedule
)
end
let(:incomplete_task) do
Task.create!(
size: 1,
project: behind_schedule
)
end
it 'renders the index page with correct dom elements' do
on_schedule.tasks << completed_task
behind_schedule.tasks << incomplete_task
@projects = [on_schedule, behind_schedule]
render
within("#project_#{on_schedule.id}") do
expect(rendered).to have_selector('.on_Schedule')
end
expect(rendered).to have_selector(
"#project_#{on_schedule.id} .on_schedule"
)
expect(rendered).to have_selector(
"#project_#{behind_schedule.id} .behind_schedule"
)
end
end

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 ...