I am writing RSpec tests to make sure my database associations work properly. I noticed that immediately after resetting the database, my tests always fail. They always expect an object but get nil instead. I also noticed that immediately after writing a new test, the new test will fail. If I run the test suite once again and the tests were correct to begin with, they all pass.
How do I make my tests pass immediately after a test database reset?
Here's a sample test file:
describe 'Player' do
let(:clan) {Clan.first || Clan.create(name: "Test Clan")}
let(:kingdom) {Kingdom.first || Kingdom.create}
let(:player) {Player.first || Player.create(username: "Foo", uuid: "9b15dea6-606e-47a4-a241-420251703c59", clan_id: 1, clan_role: "member", kingdom_id: 1, kingdom_role: "pleb")}
let(:ip_address) {IpAddress.first || IpAddress.create(ip: "55.55.555.55")}
let(:punishment) {Punishment.first || Punishment.create(offender_id: 1)}
let(:connection) {Connection.first || Connection.create(player_id: 1, ip_address_id: 1)}
let(:bank_account) {BankAccount.first || BankAccount.create(account_owner_id: 1)}
let(:sell_offer) {SellOffer.first || SellOffer.create(seller_bank_account_id: 1, item_id: 1)}
let(:buy_offer) {BuyOffer.first || BuyOffer.create(buyer_bank_account_id: 1, item_id: 1)}
let(:owned_item) {OwnedItem.first || OwnedItem.create(owner_bank_account_id: 1, item_id: 1)}
context 'associations' do
it 'has ip addresses' do
expect(player.ip_addresses.first).to eq(ip_address)
end
it 'has connections' do
expect(player.connections.first).to eq(connection)
end
it 'has punishments' do
expect(player.punishments.first).to eq(punishment)
end
it 'has a clan' do
expect(player.clan).to eq(clan)
end
it 'has a bank account' do
expect(player.bank_account).to eq(bank_account)
end
it 'has sell offers' do
expect(player.sell_offers.first).to eq(sell_offer)
end
it 'has buy offers' do
expect(player.buy_offers.first).to eq(buy_offer)
end
it 'has owned items' do
expect(player.owned_items.first).to eq(owned_item)
end
it 'has a kingdom' do
expect(player.kingdom).to eq(kingdom)
end
end
context 'class methods' do
# stuff
end
end