Ben
Ben

Reputation: 5182

Using let does not save the record

Give the below simple example :

let(:item) { create(:item }
it 'query by scope' do
  expect(Item.all.length).to eq 1
end

The test does not pass.

Adding item.save within the it block, the test pass. Using a before(:each) { create(:item) } instead of let make the test pass too.

Sounds obvious, as the point I might be missing, why is let not effectively creating the record in this case?

Upvotes: 2

Views: 595

Answers (1)

Greg
Greg

Reputation: 6648

Please use let! instead. let is lazily evaluated, let! body is called immediately.

All the examples you provided are valid because of let being lazily evaluated. You could also just call item inside it (without save) and it should pass as well.

Upvotes: 3

Related Questions