Testing an index page in a web application where we depend on the order.
[Everyday Code]
Today the specs for an index page failed and I had to improve it. I decided to share a little trick for when we depend on the order of the objects.
The specs is for the /subscriptions page where we show an index of all the subscriptions. We order the subscriptions by created_at in DESC. There are 20 subscriptions on the page. Then you must got to the next page. In the spec we open the page and check that there is a link to our subscription.
visit "/admin/user/subscriptions"
expect(page).to have_link subscription.random_id.to_s, href: "/admin/user/subscriptions/#{subscription.to_param}/edit"
The problem was that there are other specs which for some reason create subscriptions into the future. This means that at a certain point in time when more than 20 subscriptions are created into the future in the DB, then our spec will fail. It will fail because the newly created subscription is on the second page.
All the subscriptions on this page are into the future as today is 2020-11-30. So our newly created subscription is not here.
What are our options?
Move to the correct page in the spec
This is an option. It will require us to have a loop in the spec that would more to the next page in the index and search for each subscription. This is too much logic for a spec.
Delete all the future subscriptions before starting the spec
Could be done. But is more logic for the spec. It actually needs to delete subscriptions and this is not the job of this specs.
Create a subscription that is with the most recent created_at
It is simple.
let(:subscription) {FactoryBot.create(:subscription, created_at: subscription_created_at_time)}
def subscription_created_at_time
(Subscription.order(:created_at).last.try(:created_at) || Time.now)+1.second
end
It is the simpler change for this spec. Just create a subscription that’s last. In this way we know it will appear on the first page even when other specs have created subscriptions into the future.
Reply
You must be logged in to post a comment.