2012-01-26 48 views
33

我正在編寫一個應用程序,希望檢查視圖是否有而不是具有某些功能 - 特別是因爲該功能只能呈現給特定安全組中的用戶。我正在尋找與assert_selects相反的命令,以便看到呈現的菜單是而不是assert_select的反義詞?

回答

41

看看該文檔在這裏:

http://apidock.com/rails/ActionController/Assertions/SelectorAssertions/assert_select

從文檔:

assert_select是assertion that selects elements and makes one or more equality tests.

和來自平等測試s ections:

的相等測試可以是以下之一:

真 - 如果選擇的至少一種元素斷言是真實的。

false - 如果沒有選擇元素,聲明爲true。

字符串/正則表達式 - 如果至少有一個 元素的文本值與字符串或正則表達式匹配,則聲明爲true。

整數 - 如果所選元素的數量正好是 ,則聲明爲真。

範圍 - 如果所選元素的數量符合 範圍,則聲明爲true。

如果未指定相等性測試,則如果選擇至少一個 元素,則聲明爲真。

和一個簡單的例子:

# Page contains no forms 
    assert_select "form", false, "This page must contain no forms" 
0

您可以輕鬆定義自己:

module ActionDispatch::Assertions::SelectorAssertions 
    def assert_no_select(*a,&b) # try to think of a better name! 
    begin 
     assert_select(*a,&b) 
    rescue AssertionFailedError 
     return 
    end 
    raise "fail" # there should be a better built-in alternative 
    end 
end 
+0

由於'AssertionFailedError'在評估否定之前引發,因此這不起作用。 – gertas

+0

好點!編輯。 –

26

別忘了你可以隨時通過在計數,並設置爲零。

assert_select "a", {count: 0, text: "New"}, "This page must contain no anchors that say New" 
+0

這不適用於我:即使找到元素也不會引發異常。 –

+1

更新:對於「身體」以外的任何元素都可以正常工作。 –

+0

很高興知道!謝謝@MatijsvanZuijlen – GantMan

2

我有這個問題,以確保沒有一個'刪除'按鈕,從許多按鈕中。接受的答案在這種情況下不起作用,因爲已經有幾個按鈕。

assert_select '.button' do |btn| 
    btn.each do |b| 
    assert_no_match 'Delete', b.to_s 
    end 
end 

但是,我真的很喜歡GantMan的回答!