I’m starting on my daily refactors again but this time I’m going to focus on the Redmine core codebase. With Redmine’s recent 1.0 release, I now have the flexibility to make some major changes to it’s internal code to get it ready for some new features.
To start, I wanted to use extract method to refactor a test method into a shoulda macro.
Before
1 2 3 4 5 6 7 |
class AccountControllerTest {:login => 'register'}) assert user assert_kind_of User, user end end end end |
After
1 2 3 4 5 |
# test/functional/account_controller_test.rb class AccountControllerTest {:login => 'register'}) } end end end |
1 2 3 4 5 6 7 8 9 10 11 |
# test/test_helper.rb class ActiveSupport::TestCase def self.should_create_a_new_user(&block) should "create a new user" do user = instance_eval &block assert user assert_kind_of User, user assert !user.new_record? end end end |
I’ve used this refactoring several times before to extract common test logic. Using shoulda macros in tests make them easier to read and with the help of blocks
and instance_eval
it’s easy to make them work with dynamic data.