Using let and context

This scenario is very common, and inevitably will make the test harder to read, increasing the potential for misunderstanding the intent, which in turn will increase the likelihood of mistakes being made when the test or related code is changed. Before we see how to improve the test, we will learn about the let helper:

describe AddressValidator do let(:address) { {street: "123 Any Street", city: "Anytown"} } it "valid? returns false for incomplete address" do expect(AddressValidator.valid?(address)).to eq(false) end it "missing_parts returns an array of missing required parts" do expect( AddressValidator.missing_parts(address) ).to eq([:region, :postal_code, :country]) end context "invalid characters in value" do let(:address){ ...

Get RSpec Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.