Need to check that text appears on a page once and only once
Asked Answered
U

1

6

I'm using RSpec/Capybara for Rails app testing and I need to check that one element in the view appears once and only once.

For example, in the following code, i need to make sure that task.title will appear only once in the page. As shown, I can check if it exists or not, but I could not find how to check that it appears only once.

task = FactoryGirl.create(:task)
login_as(task.user, :scope => :user)
visit tasks_index_url
expect(page).to have_content task.title
Upset answered 24/6, 2014 at 17:45 Comment(0)
L
5

Capybara's page.has_content? (an alias of page.has_text?) takes an optional number of times that the text should appear. So you can just change your expectation to be

expect(page).to have_content(task.title, count: 1)

has_text?/has_content? has several other options, which don't appear in the rdoc but are documented in the source (starting at line 234 of the current version:):

# @option options [Integer] :count (nil) Number of times the text should occur
# @option options [Integer] :minimum (nil) Minimum number of times the text should occur
# @option options [Integer] :maximum (nil) Maximum number of times the text should occur
# @option options [Range] :between (nil) Range of times that should contain number of times text occurs
Linnlinnaeus answered 24/6, 2014 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.