Testing custom rail methods

I have several models that store words as a string with each word separated by a space. I have defined model methods for deleting and adding words to a string, and the size or number of words is updated each time accordingly. There is a mistake somewhere, because the size sometimes turns out to be negative. I am wondering what is the best way to test such a situation on rails. Ideally, I would like to write a test that allows me to add a few words and delete them, checking the correct size value each time. Thank.

+3
source share
1 answer

I assume your model looks something like this? I skipped some code for simplicity, since your question is not about how to implement the word management part, but about 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 simply 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
+5
source

Source: https://habr.com/ru/post/1737714/


All Articles