[英]Testing custom rails model methods
我有許多模型將單詞存儲為字符串,每個單詞用空格分隔。 我已經定義了模型方法來刪除和添加單詞到字符串,每次相應地更新單詞的大小或數量。 某處出現錯誤,因為尺寸有時會變成負數。 我想知道,在rails中測試這種情況的最佳方法是什么。 理想情況下,我想編寫一個測試,允許我添加一些單詞並刪除它們,同時每次驗證大小的正確值。 謝謝。
我假設你的模型看起來像這樣? 為簡單起見,我省略了一些代碼,因為您的問題不是如何實現單詞管理部分,而是如何測試它。
class A
def add_word(word)
# Add the word to the string here
end
def delete_word(word)
# Find the word in the string and delete it
end
def count_words
# Probably split on " " and then call length on the resulting array
end
end
現在你可以寫一個簡單的單元測試。
require File.dirname(__FILE__) + '/../../../test_helper'
class EpisodeTest < ActiveSupport::TestCase
def test_word_count
a = new A()
assert_equal(0, a.count_words)
a.add_word("foo")
assert_equal(1, a.count_words)
assert_equal("foo", words)
a.add_word("bar")
assert_equal(2, a.count_words)
assert_equal("foo bar", words)
a.delete_word("foo")
assert_equal(1, a.count_words)
assert_equal("bar", words)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.