简体   繁体   English

测试自定义rails模型方法

[英]Testing custom rails model methods

I have a number of models that store words as a string with each words separated by a space. 我有许多模型将单词存储为字符串,每个单词用空格分隔。 I have defined model methods to delete and add words to the string and the size or number of words is updated each time accordingly. 我已经定义了模型方法来删除和添加单词到字符串,每次相应地更新单词的大小或数量。 There is an error somewhere because the size sometimes comes out to be negative. 某处出现错误,因为尺寸有时会变成负数。 I'm wondering, what is the best way to test a situation like this in rails. 我想知道,在rails中测试这种情况的最佳方法是什么。 I would ideally like to write a test that allows me to add a number of words and remove them while verifying the correct value of size each time. 理想情况下,我想编写一个测试,允许我添加一些单词并删除它们,同时每次验证大小的正确值。 Thanks. 谢谢。

I assume your model looks something like this? 我假设你的模型看起来像这样? I have omitted some code for simplicity since your question isn't about how to implement the word management piece but on how to test it. 为简单起见,我省略了一些代码,因为您的问题不是如何实现单词管理部分,而是如何测试它。

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

Now you can just write a simple unit test. 现在你可以写一个简单的单元测试。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM