Nathan / August 27, 2009, 5:27 pm
When writing unit tests I tend to 1) use factories instead of fixtures and 2) keep my factories in synch with model validations. As such, I like to write a test to ensure that out of the box a new instance of a factory object will be valid. Here is a macro to help out with that:
class ActiveSupport::TestCase
def self.should_be_valid_with_factory
klass = self.name.gsub(/Test$/, '').underscore.to_sym
should "be valid with factory" do
assert_valid Factory.build(klass)
end
end
end
Put this in your ActiveSupport::TestCase definition and it will be available in all your tests. Simply call it by name with no params:
class BuildingTest < ActiveSupport::TestCase
should_be_valid_with_factory
end
Naming for this method was inspired by a similar method in Dan Croak's Blitz plugin.
Nathan / December 12, 2008, 4:52 pm
One of the things I like most about TDD, and shoulda specifically, is that if a thought pops up of something I need to add I can add a deferred test and come back to it later. In shoulda you can do this with:
should_eventually "do something"
#or just leave off the block
should "do something"
This works great for models/controllers, but I also wanted a way to integrate a miscelanious todo list into the flow that would pop up in autotest or when running the whole test suite. To accomplish this I’ve been keeping a TodosTest in the integration tests directory:
require File.dirname(__FILE__) + '/../test_helper'
class TodosTest < ActionController::IntegrationTest
context "TODO:" do
todos = [
'add the jquery rounded corners plugin',
'add the jquery dropshadow plugin',
'scope actions in application.js to specific pages'
]
todos.each do |todo|
should_eventually todo
end
end
end
The output of this is:
* DEFERRED: TODO: should add the jquery rounded corners plugin.
* DEFERRED: TODO: should add the jquery dropshadow plugin.
* DEFERRED: TODO: should scope actions in application.js to specific pages.
Since this isn't really an integration test I usually add a line for this in the .gitignore.
Also - this is a handy bash alias to print the todo's without the deferred/should language:
alias todo="ruby test/integration/todos_test.rb | grep TODO | sed -e 's/DEFERRED: TODO: should //g'"
The cleaned up output is:
* add the jquery rounded corners plugin.
* add the jquery dropshadow plugin.
* scope actions in application.js to specific pages.