Removing duplication in RSpec I’m still relatively new to the TDD scene. I’m writing a Rails app, and some duplication immediately sticks out at me in my first model spec. How else can I approach this?

require 'spec_helper'

describe TimeEntry do

  describe "without a project" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "should not be valid" do
      entry.project = nil
      expect(entry).to_not be_valid
    end
  end

  describe "without a user" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "should not be valid" do
      entry.user = nil
      expect(entry).to_not be_valid
    end
  end

end
I don't think this could get much drier. let is not cached across examples but it is cached within examples, so you can't move that let out of the nested describe blocks.

Maybe it might be easier for you to define tests that test when the model is valid, and then have a catch-all test to fail in any other case? Unless you are testing validation messages (which I don't think you need to be testing individually, and that is out of the scope of a unit test), you don't need to know which individual field failed, only that the model is invalid and X should happen.

describe TimeEntry do
  describe "validity" do
    let(:entry) { FactoryGirl.build :time_entry }
    it "is invalid without a project" do
      entry.project = nil
      expect(entry).to_not be_valid
    end
    it "is invalid without a user" do
      entry.user = nil
      expect(entry).to_not be_valid
    end
  end
end


Alternatively you can do the above.