views:

16

answers:

1

Using Rails 3.0, I have a small bit of code that I seem to be calling in all my Unit tests.

  1. Is there a common place to put shared unit test code that won't be incorporated into both unit and functional tests? I'd rather ONLY incorporate it into the needed files, just the unit tests.

  2. I'm new to testing practices in general. Is it common in Rails to test validations (for example, test: validates_presence_of :name)? Most of my functions that test validations on a model are all basically the same (just swap in and out correct fixture and attribute name). Doesn't seem very DRY. Looking for a way to refactor.

Thanks.

A: 

You can place the code in the test/test_helper.rb file. You should already find a code fragment that looks like this

class ActiveSupport::TestCase
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
end

If the code should be used in all your tests, you can add your methods in the ActiveSupport::TestCase class. Otherwise, wrap them into a Module and mix the module where required.

It's a good practice to test validations not to test the validation itself (the validates_presence_of macro is already tested in the Rails codebase), but to make sure chances in your code don't affect your class business.

For instance, there might be validation which needs to be triggered only in specific events. Or you might want to make sure no one removed your super-secret validation on that specific model.

If you want to test your model validations, I encourage you to check out shoulda. Shoulda provides several handy methods to test your validations.

class PostTest < ActiveSupport::TestCase

  should belong_to(:user)
  should validates_presence_of(:id)

end
Simone Carletti