Search⌘ K
AI Features

A Test with a View

Explore testing views in Ruby on Rails using test-driven development. Understand how to create views, use Capybara matchers to verify HTML content, and refactor tests for reliability. This lesson guides you through making end-to-end tests pass and improving their stability by associating DOM elements with project attributes.

Making the test pass

Let’s look at that end-to-end test again:

Ruby
require "rails_helper"
RSpec.describe "adding a project", type: :system do
it "allows a user to create a project with tasks" do
visit new_project_path
fill_in "Name", with: "Project Runway"
fill_in "Tasks", with: "Choose Fabric:3\nMake it Work:5"
click_on("Create Project")
visit projects_path
expect(page).to have_content("Project Runway")
expect(page).to have_content(8)
end
end

So far, this test passes up to the point where the code completes the controller create action. At the end of that action, it redirects to projects_path, which we didn’t know when we started the end-to-end test, and it might mean that we don’t need to explicitly visit projects_path in the test. Either way, projects_path triggers a visit to the path /projects, which is routed to the index method of the ProjectController. Since there isn’t an index method, the current error is The action 'index' could not be found for ProjectsController.

We need the index method:

class CreatesProject
    attr_accessor :name, :project, :task_string

    def initialize(name: "", task_string: "")
        @name = name
        @task_string = task_string
    end

    def build
        self.project = Project.new(name: name)
        project.tasks = convert_string_to_tasks
        project
    end

    def create
        build
        project.save
    end

    def convert_string_to_tasks
        task_string.split("\n").map do |one_task|
            title, size_string = one_task.split(":")
            Task.new(title: title, size: size_as_integer(size_string))
        end
    end
    def size_as_integer(size_string)
        return 1 if size_string.blank?
        [size_string.to_i, 1].max
    end
end
Adding index method to projects_controller.rb file in app/controllers directory

Now we have an action without a view that results in the error message that starts with the following:

ActionController::MissingExactTemplate:
       ProjectsController#index is missing a template for request formats: text/html`

To get past this error, we create a blank view file at ...