需要检查文本在页面上出现且仅出现一次

Jos*_*hba 6 rspec ruby-on-rails capybara capybara-webkit ruby-on-rails-4

我正在使用 RSpec/Capybara 进行 Rails 应用程序测试,我需要检查视图中的一个元素是否出现且仅出现一次。

例如,在下面的代码中,我需要确保它只task.title在页面中出现一次。如图所示,我可以检查它是否存在,但我找不到如何检查它是否只出现一次。

task = FactoryGirl.create(:task)
login_as(task.user, :scope => :user)
visit tasks_index_url
expect(page).to have_content task.title
Run Code Online (Sandbox Code Playgroud)

Dav*_*uth 5

Capybara's page.has_content?( 的别名page.has_text?)采用可选的文本出现次数。所以你可以改变你的期望

expect(page).to have_content(task.title, count: 1)
Run Code Online (Sandbox Code Playgroud)

has_text?/has_content?还有其他几个选项,这些选项没有出现在rdoc中,但在源代码中进行了记录(从当前版本的第 234 行开始:):

# @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
Run Code Online (Sandbox Code Playgroud)