Get those instance variables out of my specs!

code
Brian Cardarella

CEO & Founder

Brian Cardarella

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:

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

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.

Newsletter

Stay in the Know

Get the latest news and insights on Elixir, Phoenix, machine learning, product strategy, and more—delivered straight to your inbox.

Narwin holding a press release sheet while opening the DockYard brand kit box