Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using expect and should in RSpec

There is the following RSpec code:

it 'is not valid if name is not present' do
    @car.name = nil
    expect(@car).to be_invalid
end

I read "Testing with RSpec" by Aaron Sumner now, and he writes about new styles in RSpec. Earlier I wrote the following code:

it 'is not valid if name is not present' do
    @car.name = nil
    it { should_not be_valid }
end

Please, tell me, do I right? Thanks.

like image 807
malcoauri Avatar asked Feb 27 '14 11:02

malcoauri


Video Answer


2 Answers

I think this is a good example

describe "Car"
  describe '#valid?' do
    context 'when its name is nil' do
      let(:car) { FactoryGirl.create(:car, :name => nil) }

      it 'is not valid' do 
        expect(car).to_not be_valid
      end
    end
  end
end

Find more about better specs here

like image 164
Rafa Paez Avatar answered Sep 28 '22 04:09

Rafa Paez


Use the let API instead of the using @car, so that you won't risk changing the state from test to test, in a way which might break tests in unpredictable manner.

The it one-liner refers to the subject so to make your second style work it should look like that:

describe '#valid?' do
  let(:car) do
    # make your car here
  end

  subject { car } # <- this is the important line to make it work...

  before do
    car.name = nil
  end

  it { should_not be_valid }
end
like image 25
Uri Agassi Avatar answered Sep 28 '22 04:09

Uri Agassi