2012-08-16 74 views
15

使用Cucumber和Capybara,有沒有一種方法來驗證一個字符串不存在於頁面上?黃瓜/水豚:檢查一個頁面沒有內容?

例如,我將如何寫此步驟的相反:

Then /^I should see "(.*?)"$/ do |arg1| 
    page.should have_content(arg1) 
end 

此傳遞如果arg1存在。

如何找到失敗的步驟如果找到arg1

回答

24

http://rubydoc.info/github/jnicklas/capybara/master/Capybara/Node/Matchers#has_no_text%3F-instance_method

中有水豚一個has_no_content匹配。所以,你可以寫

Then /^I should not see "(.*?)"$/ do |arg1| 
    page.should have_no_content(arg1) 
    end 
+1

我很驚訝這比'assert!page.has_content?(arg)' – 2015-03-11 14:43:18

+0

@MichaelDiscenza快多少,你是對的,查看更多信息 - https://github.com/ngauthier/capybara-slow_finder_errors – 2016-01-07 18:08:47

-3

哦,等等,我想通了。這工作:

Then /^I should see "(.*?)"$/ do |arg1| 
    page.has_content?(arg1) == false 
end 
+5

您的代碼不主張的內容。我想如果你改變錯誤爲真,你的測試仍然會通過。 – 2013-09-04 15:28:12

+0

這讓我絆了好幾次。要麼使用'assert page.has_content ...'或'page.should have_content ...'不能將兩個樣式混合在一起。好電話,@PhilippeRathé。 – Tass 2015-10-09 17:10:44

8

您還可以,如果你想要讀好一點的使用should_not

Then /^I should not see "(.*?)"$/ do |arg1| 
    page.should_not have_content(arg1) 
end 

一些更多的信息:https://www.relishapp.com/rspec/rspec-expectations/docs

+0

請注意,這將只適用於JavaScript測試,如果你有你的規格包括Capybara :: RSpecMatchers。我只是遇到了這個問題:http://stackoverflow.com/a/15253235/125377 – Ari 2013-03-06 21:02:26

+11

改爲使用'has_no_content?'。這將觸發水豚的內部等待。否則,如果您等待內容從頁面中消失,則會過早失敗。 – keithepley 2013-08-20 19:31:20

3
目前

,你可以使用:

Then /^I not see "(.*?)"$/ do |arg1| 
    expect(page).to have_no_content(arg1) 
end 

如果在頁面中找到內容,測試是紅色

+0

這是正確的語法。如果您使用的是expect(),那麼我會重新說明您的規範,從描述中刪除「should」。更自信! :) – Rimian 2015-12-01 00:31:42

+0

謝謝@Rimian。我修好了! – 2016-03-23 14:01:51

10

在Rspec的3.4目前(2016),這是測試沒有內容的推薦方法:

expect(page).not_to have_content(arg1) 
+0

你認爲在'expect(page).to have_no_content(arg1)''上推薦這麼做?似乎沒有辦法讓not_to知道不要等待頁面上的內容,這就是'have_content'會做的事情,我想。 – Ibrahim 2016-12-01 01:05:57

+0

棄用警告在使用'expect(page).to have_no_content(arg1)' – 2016-12-18 17:32:08

+0

@RobHughes時顯示,您所說的折舊警告必須已在rspec 3.5.4/capybara 2.6.2中刪除。根據文檔:https://github.com/teamcapybara/capybara#asynchronous-javascript-ajax-and-friends - 然而,Capybara的RSpec匹配器足夠聰明,可以處理任何一種形式。以下兩個語句在功能上是等效的:expect(page).not_to have_xpath('a'),expect(page).to have_no_xpath('a')' – seanriordan08 2017-04-21 13:27:06