测试自定义rails模型方法

Ten*_*ack 3 testing ruby-on-rails

我有许多模型将单词存储为字符串,每个单词用空格分隔.我已经定义了模型方法来删除和添加单词到字符串,每次相应地更新单词的大小或数量.某处出现错误,因为尺寸有时会变成负数.我想知道,在rails中测试这种情况的最佳方法是什么.理想情况下,我想编写一个测试,允许我添加一些单词并删除它们,同时每次验证大小的正确值.谢谢.

Ran*_*mon 5

我假设你的模型看起来像这样?为简单起见,我省略了一些代码,因为您的问题不是如何实现单词管理部分,而是如何测试它.

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
Run Code Online (Sandbox Code Playgroud)

现在你可以写一个简单的单元测试.

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
Run Code Online (Sandbox Code Playgroud)