Sometimes in Rails you ask yourself: how do I test this?
One example is ActiveRecord
associations.
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
end
Now from the documentation for ActiveRecord::Base#has_many
we know it’s going
to generate a method for us called #comments, so let’s test that.
def test_should_have_many_comments
post = Post.new
assert_respond_to post, :comments
end
Here all we’re testing is that a Post
object understands #comments.
Maybe thats not enough?
def test_should_have_many_comments
post = Post.new
assert_respond_to post, :comments
assert_kind_of Array, post.comments
end
Now we’ve added an additional assertion to check that the object returned from
Post#comments
is an Array
.
Can we take it any further?
def test_should_have_many_comments
post = Post.new
assert_respond_to post, :comments
assert_kind_of Array, post.comments
assert_raises(ActiveRecord::AssociationTypeMismatch) {
post.comments << Post.new
}
assert_nothing_raised { post.comments << Comment.new }
end
Now we’ve added 2 additional assertions that check that the object returned from
Post#comments
only allows Comment
objects to be added to it via #<<.
OK, so maybe that might have been overkill, but at the very least you should check the object understands the given message a la our first attempt.
Another example is testing methods added to a class via a plugin.
class Article < ActiveRecord::Base
acts_as_solr
end
From the acts_as_solr
documentation it
looks like calling the acts_as_solr
class method on an ActiveRecord::Base
class object will add a #find_by_solr
method to it.
Here’s our test.
def test_should_understand_find_by_solr
assert_respond_to Article, :find_by_solr
end
There is no need to test specific solr queries and then run assertions on the
results. Once you go that route, you are now testing the acts_as_solr
plugin
and the solr
web application; this is not your application’s responsibility,
its the author(s) of acts_as_solr
and solr
to test their own code.
You’re also introducing an external dependency in your tests (that a Java
application server is running the solr
web application). Like any external
dependency, this is going to slow your tests down considerably. And once your
tests start getting slower developers are not going to be running them as much.
And if you aren’t running your tests your code is going to go south.