...

/

Expectations and lit

Expectations and lit

Learn about Rspec and Rspec matchers and how to remove duplicates from the test in the project_spec.rb file

In addition to examining code for potential refactoring, it’s a good idea to look at the duplication tests.

Press + to interact
require "rails_helper"
RSpec.describe Project do
it "considers a project with no tasks to be done" do
project = Project.new
expect(project.done?).to be_truthy
end
it "knows that a project with an incomplete task is not done" do
project = Project.new
task = Task.new
project.tasks << task
expect(project.done?).to be_falsy
end
end

In this case, in the spec/models/project_spec.rb file, we have a single line of common setup, project = Project.new, which is shared between the two tests we’ve already written. We can fix this and turn our tests into slightly more idiomatic RSpec:

rsync -avr --progress /usercode/* /usr/local/educative/gatherer --exclude Gemfile --exclude Gemfile.lock --exclude execute_.sh
cd /usr/local/educative/gatherer
clear
bundle exec rspec
Fixing the test in the project_spec.rb file

This version of the test shows two parts of RSpec:

  • The let statement
  • Dynamic matchers

About let

RSpec’s let statement cleans up the creation of test data.

Using let, we can make a variable available within the current describe block without placing it inside the before block and without having to make it an instance variable. We use let all the time. We like that it separates each variable’s definition, that it encourages concise initializations, and that the word let allows me to pretend we’re writing in Scheme or Elm for a brief moment.

The let syntax

Each let method call takes a symbol argument and a block. The symbol can then be called as if it were a local variable: the first call to the symbol lazily invokes the block ...