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. 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.
+2
A:
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
Randy Simon
2010-03-19 17:34:42