GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS

Written by thoughtbot

its not your responsibility

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 actsassolr documentation it looks like calling the actsassolr class method on an ActiveRecord::Base class object will add a #findbysolr 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 actsassolr plugin and the solr web application; this is not your application’s responsibility, its the author(s) of actsassolr 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.