Capybara: Testing for time to be present and visible on the page

Nikhil Vijayan
2 min readFeb 2, 2019

--

Source: https://pixabay.com/en/icon-checklist-flat-check-mark-2174805/

I was trying to write a test for a feature where it checks that a<li> item displays the time the item was created in the database, and ran into an issue as I don’t expect to use a lot of stubbing while writing capybara tests.

The issue here was that I create a new item in the test database, which gets saved with a certain timestamp, which I then display on the page. However, the item is created dynamically using Time.now making it harder to test.

I tried stubbing this method using something like

allow(Time).to receive(:now).and_return(<a_specific_time>)

…which failed spectacularly (it caused capybara to get stuck on the post request page when the form on the page was submitted).

Attempt 1: Using regular expressions

I ended up with a test that used regular expression:

scenario 'a user can see the time the list item was made' do  visit('/')  fill_in('text_field', with: 'Lorem Ipsum')  click_button('Post')  expect(current_path).to eq('/')  expect(first('.classname')).to have_text(/\d{2}:\d{2}:\d{2}/)end

What this ^ test is testing for is that a time is displayed in the form of XX:XX:XX where X = any number. This works, however is very brittle as a small change can cause this test to fail, and having to rewrite it.

Attempt 2: Checking for the presence of the specific item

This is what I ended up with:

scenario 'a user can see the time the list item was made' do  visit('/')  fill_in('text_field', with: 'Lorem Ipsum')  click_button('Post')  expect(current_path).to eq('/')  page.find('#item_id', :visible => true)end

Here, I’m testing if that specific item gets rendered and is displayed.

Foiled attempt worth mentioning in case it is useful to someone else

I also tried using the Timecop Gem to stub time, however this didn’t work for me in this instance.

If you have a better way of testing for this situation, please leave a comment! I created this post as I couldn’t find many SO threads dealing with this.

Get updates when I publish a new story or something. I'm a junior developer hoping to document as much of my learnings as possible.

--

--

Nikhil Vijayan
Nikhil Vijayan

No responses yet