Get those instance variables out of my specs!

If you've been writing RSpec for any period of time I'm sure you've come across let and subject. (please take a moment to check out the links if you have no idea what I'm talking about) In most cases you can write the same specs with instance variables. For example:

1
2
3
4
5
6
7
8
9
10
11
12
describe '.find_good_cars' do
  before do
    @car_1 = Factory(:good_car)
    @car_2 = Factory(:good_car)
    @car_3 = Factory(:bad_car)
    @good_cars = Car.find_good_cars
  end

  it 'only finds good cars' do
    @good_cars.should eq [@car_1, @car_2]
  end
end

Here is what it looks like when using let and subject

1
2
3
4
5
6
7
describe '.find_good_cars' do
  let!(:car_1) { Factory(:good_car) }
  let!(:car_2) { Factory(:good_car) }
  let!(:car_3) { Factory(:bad_car)  }
  subject      { Car }
  its(:find_good_cars) { should eq [car_1, car_2] }
end

Maybe it is just me but this feels cleaner. I treat instance variables in my specs as a smell and you should too.

Contact us about our design & engineering services!
Tweet

Stay in the know.

Introducing the DockYard Newsletter. Our best design and engineering articles, conveniently delivered to your inbox each month. Sign up below!