2017-03-15 57 views
0

我正在通過Michael Hartl的rails教程,並且在6.2.2中,UserTest包含'name should be present'的測試。該測試包括代碼'assert_not user.valid?'與'斷言user.invalid?'

test 'email should be present' do 
    @user.email = " "  
    assert_not user.valid? 
end 

和在測試失敗時,下面是輸出:

FAIL["test_name_should_be_present", UserTest, 0.10366088798036799] 
test_name_should_be_present#UserTest (0.10s) 
     Expected true to be nil or false 

如果更改斷言到

test 'email should be present' do 
    @user.email = " " 
    assert user.invalid? 
end 

失敗測試輸出是

FAIL["test_name_should_be_present", UserTest, 0.11991263600066304] 
test_name_should_be_present#UserTest (0.12s) 
     Expected false to be truthy. 

是有一種測試會失敗而不是另一種的情況,還是可以互換的? '斷言。無效?'對我來說似乎更自然。

順便說一句,測試失敗,因爲測試寫在驗證電子郵件存在的代碼寫入之前。

+0

您能否從測試中顯示完整的代碼? –

+0

還有'反駁user.valid?',但我對這個有着複雜的感受:) –

回答

0

是的,它們是等價的。

.valid?並且無效?會給你真或假,而assert_not期望無或假,斷言會期望一個非零對象或真實。

假設@user是無效的,那麼你可以:

assert_not @user.valid? 
#valid will give you false, so 'assert_not false' is true, and the test passes. 
,另一方面

assert @user.invalid? 
#invalid will give you true, so 'assert true' is true, and the test passes. 

你可以做同樣的道理,如果我們改變假設,@user是有效的。

+0

這是我的假設。謝謝。 – froglegs

+0

不要忘記檢查答案是否正確:) – Gaston