🖥
What is difference of Rails + rspec let VS let! (bang or not bang?) :
require "rails_helper"
# There cases all pass
describe do
context do
let!(:user) { create :user, name: 'Alice' }
# it create a record before expect "user" in spec
it do
expect(User.count).to eq 1
expect(user.name).to eq 'Alice'
expect(User.count).to eq 1
end
end
context do
let(:user) { create :user, name: 'Bob' }
# it does not create a record before expect "user" in spec
it do
expect(User.count).to eq 0
expect(user.name).to eq 'Bob'
expect(User.count).to eq 1
end
end
end
describe do
context do
# Let bang and same let names
# It does not create three records
# only last let! evaluated
let!(:user) { create :user, name: 'Alice' }
let!(:user) { create :user, name: 'Bob' }
let!(:user) { create :user, name: 'Carol' }
it do
expect(User.count).to eq 1
expect(user.name).to eq 'Carol'
expect(User.count).to eq 1
end
end
context do
# Different let names
# It create each three records
let!(:user1) { create :user, name: 'Alice' }
let!(:user2) { create :user, name: 'Bob' }
let!(:user3) { create :user, name: 'Carol' }
it do
expect(User.count).to eq 3
expect(user1.name).to eq 'Alice'
expect(user2.name).to eq 'Bob'
expect(user3.name).to eq 'Carol'
expect(User.count).to eq 3
end
end
end
Original by Github issue
チャットメンバー募集
何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。
公開日時
2019-12-17
Discussion