2012-02-02 56 views
1

我正在爲rails中的簡單用戶模型編寫單元測試,並開始考慮如何編寫測試。我是否應該測試正面和負面的陳述?

似乎是積極的測試:

test "password should match the password_confirmation " do 
    user = User.new(
    :email => "[email protected]", 
    :password => "password", 
    :password_confirmation => "password") 
    assert user.valid?, "did not save user even though password matches confimation" 
    end 

和負面測試:

test "password should not be valid with mismatching password_confirmation " do 
    user = User.new(
    :email => "[email protected]", 
    :password => "password", 
    :password_confirmation => "doesnotmatch") 
    assert user.invalid?, "saved user with mismatching password_confirmation" 
    end 

它是多餘的,包括你的測試套件這兩個測試或者是一個好的做法呢?

回答

1

看看TDD. When you can move on?,這解釋了什麼時候你準備好了測試(和代碼)並可以繼續前進。在你的例子中,這意味着:

  • 你首先寫出積極的測試。測試失敗。
  • 然後編寫必要的代碼,以便測試成功。
  • 之後,你需要另一個測試來證明你的實現是不夠的。當你寫完例如

    class User 
        def initialize(hash) 
        @hash = hash 
        end 
        def valid? 
        true 
        end 
    end 
    

    您需要另一個測試用例來證明錯誤。

  • 編寫下一個測試用例,這表明檢查密碼可能會失敗。

我看到下面的情況:

  • 沒有密碼
  • 匹配的密碼(但太短)
  • 匹配的密碼(長,夠難)
  • 不匹配的密碼

所以你需要4個測試用例。

0

我會說這是個好主意,因爲知道這些測試中的任何一個並不意味着其他人會這樣做。