Build Robust & Production Quality Applications - Lesson 2: Alternative Style of Rspec

An Alternative Style of Rspec

Uses lazy evaluation which means it doesn't evaluate the :todo or the subject until it has to ...namingly when it reaches it or before.

To avoid lazy evaluation, you could do:

let!(:todo) {Todo.create(name: "cook dinner")}

Pros:

is more concise and separates the common set up code using lets

Cons:

For a lengthy test suite it may be hard to connect the test with the description.

Using let

Step 1. Eliminate the repetition of Todo.create in each test:

describe "#display_text" do
  let(:todo) { Todo.create(name: "cook dinner") }

Step 2. Replace todo.display_ text

describe "#display_text" do
  let(:todo) { Todo.create(name: "cook dinner") }
  let(:subject) { todo.display_text }

or

Step3. Replace todo.display_text

describe "#display_text" do
  let(:todo) { Todo.create(name: "cook dinner") }
  subject { todo.display_text }

Using before for case specific tests

context "displays the name when there's no tags" do
  it "displays the name when there's no tags" do
    subject.should == "cook dinner"
  end
end

context "displays the only tag with word 'tags' when there's one tag"
  before do
    todo.tags.create(name: "home")
    todo.tags.create(name: "urgent")
  end
  it "displays name with multiple tags" do
    subject.should == "cook dinner (tags: home, urgent)"
  end
end

Change lengthy context to more succinct:

context "displays the only tag with word 'tags' when there's one tag"

to =>

context "multiple tags"

Remove the "it -text-" because its in context with the description

context "one tag" do
  before { todo.tags.create(name: "home") }
  it { should == "cook dinner (tag: home)" }
end