Working with Rails

Recommend Brian on Working With Rails


Powered

Building Tempo with Rails, Part III

Posted by Brian Sam-Bodden Wed, 31 Oct 2007 22:00:00 GMT

Rails

Now that we have a basic understanding of BDD with RSpec let's pick a business critical user story and build it from tests outwards. With Tempo being a time tracking system the most crucial story should be a "User enters Time".

TimeEntry

At the core of this story is the model class TimeEntry. In Tempo we want users to be able to enter time by:

  • a) picking a beginning time an an end time for a given date
  • b) picking a beginning date-time and an end date-time

For billing purposes it is usually convenient to split the hours in a range of date-times into chunks of hours per day (for the ranges that span over multiple days). The way I envision these two entry methods are:

  • a) a simple page that defaults to the current date and that allows the user to pick two times for the given day along with other information required (project, activity, etc.)
  • b) a page with two date/time pickers that enables the user to pick a range (or some fancier UI control if I can find one)

In the spirit of TDD let's start with the skeleton RSpec specification for TimeEntry. In the spec/models directory of the application create the Ruby file time_entry_spec.rb:

describe TimeEntry do

  before do
    @time_entry = TimeEntry.new
  end

  it "should be invalid without an associated User" do
  end

  it "should be invalid without an associated Project" do
  end

  it "should be invalid without an associated Project Activity" do
  end

  it "should know that it needs to be split across days" do
  end

  it "should know how to split a time entry across multiple days" do
  end

  it "should not have a value higher than 24 hours" do
  end

end

Notice that I've added an expectation that a given time entry should know that it needs to be split across multiple days and it also should know how to perform this split.

If I run the tests now they should obviously fail. We don't even have a TimeEntry class in place:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
/.../lib/active_support/dependencies.rb:266:in `load_missing_constant': uninitialized constant TimeEntry (NameError)

Let's get pass that one problem and create the model:

script/generate rspec_model TimeEntry
      exists  app/models/
      exists  spec/models/
      exists  spec/fixtures/
      create  app/models/time_entry.rb
      create  spec/fixtures/time_entries.yml
overwrite spec/models/time_entry_spec.rb? [Ynaqd] n
        skip  spec/models/time_entry_spec.rb
      exists  db/migrate
      create  db/migrate/004_create_time_entries.rb
/> 

Notice that the generate task will try to overwrite the spec we just wrote so answer NO (n) to the overwrite question as shown above. Let's add the basic fields we would expect to find in our TimeEntry class/table:

class CreateTimeEntries < ActiveRecord::Migration
  def self.up
    create_table :time_entries do |t|
      t.column :user_id, :integer
      t.column :project_id, :integer 
      t.column :projects_activity_id, :integer
      t.column :start, :datetime
      t.column :end, :datetime
      t.column :hours, :float
      t.column :comment, :string 
    end
  end

  def self.down
    drop_table :time_entries
  end
end

Run the migration to get the table created:

rake db:migrate
(in /Users/bsbodden/Documents/projects/tempo)
== CreateTimeEntries: migrating ===============================================
-- create_table(:time_entries)
   -> 0.0414s
== CreateTimeEntries: migrated (0.0416s) ======================================

If we run the tests, they all pass now, that's not good, not quite TDD, so let's add some substance and break things as they should:

Let's start with the easy stuff:

  before do
    @time_entry = TimeEntry.new
    @user = User.new
  end

  it "should be invalid without an associated User" do
    @time_entry.should_not be_valid
    @time_entry.errors.on(:user).should eql("must have an associated user")
    @time_entry.user = @user
    @time_entry.should be_valid
  end 

Run the tests again and we now have our first 'expected' failure:

1)
'TimeEntry should be invalid without an associated User' FAILED
expected valid? to return false, got true
./spec/models/time_entry_spec.rb:14:

Finished in 0.06691 seconds

8 examples, 1 failure

As we learned in part II, to pass this test we need a one liner to add an ActiveRecord validation:

class TimeEntry < ActiveRecord::Base
  has_one :user

  validates_presence_of :user, :message => 'must have an associated user'
end

Test again to confirm that the validation test passes:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
........

Finished in 0.071294 seconds

8 examples, 0 failures

Next one down the line is the test for an associated project:

  before do
    @time_entry = TimeEntry.new
    @user = User.new
    @project = Project.new
  end

  it "should be invalid without an associated Project" do
    @time_entry.should_not be_valid
    @time_entry.errors.on(:project).should eql('must have an associated project')
    @time_entry.project = @project
    @time_entry.should be_valid
  end

Running the test again should confirm that we do not have a Project model yet:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
..FFFFFF

1)
NameError in 'TimeEntry should not have a value higher than 24 hours if expressed as a single hour value'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

2)
NameError in 'TimeEntry should be broken into two or more TimeEntry instances if it date-time range spans over multiple days'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

3)
NameError in 'TimeEntry should either consist of a date-time range or a single hour value'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

4)
NameError in 'TimeEntry should be invalid without an associated Project Activity'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

5)
NameError in 'TimeEntry should be invalid without an associated Project'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

6)
NameError in 'TimeEntry should be invalid without an associated User'
uninitialized constant Project
./spec/models/time_entry_spec.rb:12:

Finished in 0.121636 seconds

8 examples, 6 failures

Add the Project model to the mix using the rake task:

script/generate rspec_model Project  
      exists  app/models/
      exists  spec/models/
      exists  spec/fixtures/
      create  app/models/project.rb
      create  spec/fixtures/projects.yml
      create  spec/models/project_spec.rb
      exists  db/migrate
      create  db/migrate/005_create_projects.rb

Modify the migration to add the basic fields expected in a Project:

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.column :name, :string
      t.column :description, :string
      t.column :owner_id, :integer
    end
  end

  def self.down
    drop_table :projects
  end
end

and run the migration:

rake db:migrate
(in /Users/bsbodden/Documents/projects/tempo)
== CreateProjects: migrating ==================================================
-- create_table(:projects)
   -> 0.0377s
== CreateProjects: migrated (0.0380s) =========================================

Let's test again with the Project model in place:

/> rake spec
(in /Users/bsbodden/Documents/projects/tempo)
......F..

1)
'TimeEntry should be invalid without an associated Project' FAILED
expected "must have an associated project", got nil (using .eql?)
./spec/models/time_entry_spec.rb:24:

Finished in 0.081038 seconds

9 examples, 1 failure

Great, now we broke what we wanted to break ;-)

Let's now add the validations for project:

class TimeEntry < ActiveRecord::Base
  has_one :user
  has_one :project

  validates_presence_of :user, :message => 'must have an associated user'
  validates_presence_of :project, :message => 'must have an associated project'
end

Let's test one more time:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
......FF.

1)
'TimeEntry should be invalid without an associated Project' FAILED
expected valid? to return true, got false
./spec/models/time_entry_spec.rb:26:

2)
'TimeEntry should be invalid without an associated User' FAILED
expected valid? to return true, got false
./spec/models/time_entry_spec.rb:19:

Finished in 0.083707 seconds

9 examples, 2 failures

Let's fix our problems by adding a module with a helper create method for TimeEntries and we'll just nil the associations that we are looking to test:

module TimeEntrySpecHelperMethods
  def create_time_entry(options = {})
    @user = User.new
    @project = Project.new
    TimeEntry.create({ :user => @user, :project => @project }.merge(options))
  end
end

describe TimeEntry do

  include TimeEntrySpecHelperMethods

  it "should be invalid without an associated User" do
    time_entry = create_time_entry(:user => nil)
    time_entry.should_not be_valid
    time_entry.errors.on(:user).should eql('must have an associated user')
    time_entry.user = @user
    time_entry.should be_valid
  end

  it "should be invalid without an associated Project" do
    time_entry = create_time_entry(:project => nil)
    time_entry.should_not be_valid
    time_entry.errors.on(:project).should eql('must have an associated project')
    time_entry.project = @project
    time_entry.should be_valid
  end

Pending Tests in RSpec

What do you know! it always helps to have an expert near by, Joe O'brien from the EdgeCase just stopped by and schooled me on some of the subtleties of RSpec. If you remember I started with a skeleton for a test that was passing and that's not quite following TDD since we should have a test that initially fails. Otherwise, in a team environment there is a big chance that we will "forget" to implement the test.

A very useful trick when you are "scaffolding your tests" like I was is to remove the block, that is the do..end and RSpec will report the tests as pending. So my test now looks like:

require File.dirname(__FILE__) + '/../spec_helper'

module TimeEntrySpecHelperMethods
  def create_time_entry(options = {})
    @user = User.new
    @project = Project.new
    TimeEntry.create({ :user => @user, :project => @project }.merge(options))
  end
end

describe TimeEntry do

  include TimeEntrySpecHelperMethods

  it "should be invalid without an associated User" do
    time_entry = create_time_entry(:user => nil)
    time_entry.should_not be_valid
    time_entry.errors.on(:user).should eql('must have an associated user')
    time_entry.user = @user
    time_entry.should be_valid
  end

  it "should be invalid without an associated Project" do
    time_entry = create_time_entry(:project => nil)
    time_entry.should_not be_valid
    time_entry.errors.on(:project).should eql('must have an associated project')
    time_entry.project = @project
    time_entry.should be_valid
  end

  it "should be invalid without an associated Project Activity"

  it "should know that it needs to be split across days" 

  it "should know how to split a time entry across multiple days" 

  it "should not have a value higher than 24 hours" 

end

Notice the do..ends are gone in the unimplemented tests. When we run the test we now get:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...PPPP..

Finished in 0.074545 seconds

9 examples, 0 failures, 4 pending

Pending:
TimeEntry should know that it needs to be split across days (Not Yet Implemented) 
TimeEntry should not have a value higher than 24 hours (Not Yet Implemented)
TimeEntry should know how to split a time entry across multiple days (Not Yet Implemented) 
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented) 

Now that is cool! Thanks Joe.

Next we'll tackle a more challenging test and associated functionality:

TimeEntry "should know that it needs to be split across days"

This test should check that a TimeEntry can detect that it spans over multiple days. The test is simple, set the start and end dates so that they span over multiple days and check that a method, let's call it "needs_splitting" returns true.

  it "should know that it needs to be split across days" do
    time_entry = create_time_entry
    time_entry.start = 2.hours.ago(Time.today.beginning_of_day)
    time_entry.end = 5.hours.since(time_entry.start)
    time_entry.needs_splitting.should be_true
  end 

Run the test and watch it fail:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...PFP..

1)
NoMethodError in 'TimeEntry should know that it needs to be split across days'
undefined method `needs_splitting' for #
./spec/models/time_entry_spec.rb:40:

Finished in 0.088024 seconds

8 examples, 1 failure, 3 pending

We need a 'needs_splitting' method:

class TimeEntry < ActiveRecord::Base
  has_one :user
  has_one :project

  validates_presence_of :user, :message => 'must have an associated user'
  validates_presence_of :project, :message => 'must have an associated project'

  def needs_splitting
    false
  end
end

testing again should now gives us failing test:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...PFP..

1)
'TimeEntry should know that it needs to be split across days' FAILED
expected true, got false
./spec/models/time_entry_spec.rb:40:

Finished in 0.127189 seconds

8 examples, 1 failure, 3 pending
TimeEntry should not have a value higher than 24 hours (Not Yet Implemented)
TimeEntry should know how to split a time entry across multiple days (Not Yet Implemented) 
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented) 

To pass the test we can simply check that the day on the end Time is greater than the day on the start Time:

  def needs_splitting
    self.start.day < self.end.day
  end

Now we can run the test, passing with flying colors:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...P.P..

Finished in 0.079906 seconds

8 examples, 0 failures, 3 pending
TimeEntry should not have a value higher than 24 hours (Not Yet Implemented)
TimeEntry should know how to split a time entry across multiple days (Not Yet Implemented) 
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented) 

TimeEntry "should know how to split a time entry across multiple days"

The next piece of functionality is a bit more involved. We want a method that tells us whether a TimeEntry instance spans over multiple days, if that is the case then I want to also have a method that can give me a collection of TimeEntry(s) representing all the single day interval. So here's a simple test that I think can accomplish that:

  it "should know how to split a time entry across multiple days" do
    time_entry = create_time_entry
    time_entry.start = 2.hours.ago(Time.today.beginning_of_day)
    time_entry.end = 5.hours.since(time_entry.start)
    entries = time_entry.split!
    entries.should_not be_empty
    total = 0.0
    entries.inject(0) {|total, e| total += e.total_hours}
    total += time_entry.total_hours
    total.should eql(5.0)
    time_entry.needs_splitting.should_not be_true
  end

In this test I have a start time that is 2 hours before midnight of the current day and an end date that 5 hours ahead which gives us a day crossing range. Then we call the split! method that should return a collection of one or more TimeEntry(s) each containing any hours allocated to a whole or partial day. The split! method should also modify the current TimeEntry to contain only the hours reported on the first day of the range.

In the test we also check that the total number of hours is still the same after the split and that after the split we no longer need to split (e.g. the needs_splitting should return false)

Let's add the skeleton methods for split! and total_hours:

  def split!
    remaining_time_entries = []
  end

  def total_hours
    0.0
  end

Running the test should show a failure:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...PF.P..

1)
'TimeEntry should know how to split a time entry across multiple days' FAILED
expected empty? to return false, got true
./spec/models/time_entry_spec.rb:48:

Finished in 0.144307 seconds

9 examples, 1 failure, 2 pending
TimeEntry should not have a value higher than 24 hours (Not Yet Implemented)
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented) 

Let's work out the split! method. Below is my first attempt (somehow I think my Java background might show and I welcome more rubyeske versions of this method):

  def split!
    remaining_time_entries = []
    if needs_splitting
      # save the original end time
      original_end = self.end 
      # first change the current TimeEntry to the end_of_day of the start day
      self.end = self.start.change(:hour => 23, :min => 59, :sec => 59)
      (self.start.day+1..original_end.day).each do |day|
        time_entry = self.clone
        time_entry.start = time_entry.start.change(:mday => day).beginning_of_day
        if day == original_end.day
          time_entry.end = original_end
        else
          time_entry.end = time_entry.start.change(:hour => 23, :min => 59, :sec => 59)
        end
        remaining_time_entries << time_entry
      end   
    end
    remaining_time_entries
  end

The total_hours method is fairly simple:

  # calculate total hours, round to 2 decimal places
  def total_hours
    (((self.end - self.start) / 3600) * 10**2).round.to_f / 10**2
  end

We can run the tests again and see what we have left to build:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
...P..P..

Finished in 0.15218 seconds

9 examples, 0 failures, 2 pending

Pending:
TimeEntry should not have a value higher than 24 hours (Not Yet Implemented)
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented)

TimeEntry "should not have a value higher than 24 hours"

This test if fairly simple to code, we are looking to check that TimeEntry(s) that have been split do not report more than 24 hours.

  it "should not have a value higher than 24 hours" do
    time_entry = create_time_entry
    time_entry.start = 2.hours.ago(Time.today.beginning_of_day)
    time_entry.end = 5.hours.since(4.days.since(time_entry.start))
    entries = time_entry.split!
    entries.should_not be_empty
    entries.each do |entry|
      entry.total_hours.should be <= 24.0
    end
    time_entry.total_hours.should be <= 24.0
  end 

I added a range of time that spans multiple days and then call split! and check that any of the resulting TimeEntry(s) as well as the original TimeEntry do not have more than 24 hours

Let's run the tests again:

rake spec
(in /Users/bsbodden/Documents/projects/tempo)
..............P..

Finished in 0.129319 seconds

17 examples, 0 failures, 1 pending

Pending:
TimeEntry should be invalid without an associated Project Activity (Not Yet Implemented)

TimeEntry "should be invalid without an associated Project Activity"

The final test on for TimeEntry seems fairly simple:

    time_entry = create_time_entry(:projects_activity => nil)
    time_entry.should_not be_valid
    time_entry.errors.on(:projects_activity).should eql('must have an associated project activity')
    time_entry.projects_activity = @projects_activity
    time_entry.should be_valid

If you got back to installment #2 you might remember that from the initial Tempo domain model we know that "A Project has some Project Activities associated which are a subset of a global list of Activities". Therefore we need to create a few migrations and a few models to complete to get this test to pass.

Activities

Activities are the the global set of activities. Activities can be added to a project (see Project Activities below)

First create the migration:

script/generate migration create_activities
      exists  db/migrate
      create  db/migrate/006_create_activities.rb

An Activity needs a name and a description:

class CreateActivities < ActiveRecord::Migration
  def self.up
    create_table :activities do |t|
      t.column :name, :string
      t.column :description, :string
    end
  end

  def self.down
    drop_table :activities
  end
end

Run the migration:

/> rake db:migrate
(in /Users/bsbodden/Documents/projects/tempo)
== CreateActivities: migrating ================================================
-- create_table(:activities)
   -> 0.0030s
== CreateActivities: migrated (0.0032s) =======================================

Project Users

A Project can have Users associated with it. Only users associated with a Project should be able to enter time against the Project:

Let's create the migration:

script/generate migration create_project_users
      exists  db/migrate
      create  db/migrate/007_create_project_users.rb

A Project User table associates a Project and a User. We also need a Role in this table since we will have project owners (managers) and project workers:

class CreateProjectUsers < ActiveRecord::Migration
  def self.up
    create_table :projects_users do |t|
      t.column :project_id, :integer, :null => false
      t.column :user_id, :integer, :null => false
      t.column :role_type, :integer, :null => false
    end
  end

  def self.down
    drop_table :projects_users
  end
end

Run the migration:

rake db:migrate
(in /Users/bsbodden/Documents/projects/tempo)
== CreateProjectUsers: migrating ==============================================
-- create_table(:projects_users)
   -> 0.0029s
== CreateProjectUsers: migrated (0.0031s) =====================================

Project Activities

Individual Projects will have some Activities that apply. The Project Activities table will maintain those associations:

script/generate migration create_project_activities
      exists  db/migrate
      create  db/migrate/008_create_project_activities.rb

In the table we need only the id of the Project and the Activity we are associating:

class CreateProjectActivities < ActiveRecord::Migration
  def self.up
    create_table :projects_activities do |t|
      t.column :project_id, :integer, :null => false
      t.column :activity_id, :integer, :null => false
    end
  end

  def self.down
    drop_table :projects_activities
  end
end

Run the migration:

rake db:migrate
(in /Users/bsbodden/Documents/projects/tempo)
== CreateProjectActivities: migrating =========================================
-- create_table(:projects_activities)
   -> 0.1885s
== CreateProjectActivities: migrated (0.1887s) ================================

Finishing the Models

To get the first working Models I will add some ActiveRecord associations. For a Project we have a bunch of has_many associations. You guess the obvious ones, like a:

  • A Project has many Users via the projects_users table
  • A Project has many Activities via the projects_activity table

To set those associations I am using a couple of explicit join models. The join model for Users in a Project:

class ProjectsUser < ActiveRecord::Base
  belongs_to :project
  belongs_to :user
end

and the join model for the Activities that time can be reported against for a particular Project:

class ProjectsActivity < ActiveRecord::Base
  belongs_to :project
  belongs_to :activity
end

Notice that below in the Project class I can also use the :has_many with the :through option to have a list of actual Activity objects available in the model explicitly via the join model projects_activity. Similarly we have Users and specific type of Users by using the :conditions option to filter the project_users join model:

class Project < ActiveRecord::Base
  has_many :projects_users
  has_many :projects_activity
  has_many :activities, :through => :projects_activity, :source => :activity
  has_many :users, :through => :projects_users, :source => :user
  has_many :managers, :through => :projects_users, :source => :user,
           :conditions => "projects_users.role_type = 2"
  has_many :workers, :through => :projects_users, :source => :user,
           :conditions => "projects_users.role_type = 1"
end

Update:

A reader pointed out that at this point the last test for TimeEntry; "should be invalid without an associated Project Activity" was not passing. That's not surprising since I forgot to post the code for the validations in TimeEntry.

Here's the current state of TimeEntry:

class TimeEntry < ActiveRecord::Base
  belongs_to :user
  belongs_to :project
  belongs_to :projects_activity

  attr_reader :total_hours, :date

  alias :total_hours? :total_hours

  validates_presence_of :user, :message => 'must have an associated user'
  validates_presence_of :project, :message => 'must have an associated project'
  validates_presence_of :projects_activity, :message => 'must have an associated project activity'

  def needs_splitting
    self.start.day < self.end.day
  end

  def split!
    remaining_time_entries = []
    if needs_splitting
      # save the original end time
      original_end = self.end 
      # first change the current TimeEntry to the end_of_day of the start day
      self.end = self.start.change(:hour => 23, :min => 59, :sec => 59)
      (self.start.day+1..original_end.day).each do |day|
        time_entry = self.clone
        time_entry.start = time_entry.start.change(:mday => day).beginning_of_day
        if day == original_end.day
          time_entry.end = original_end
        else
          time_entry.end = time_entry.start.change(:hour => 23, :min => 59, :sec => 59)
        end
        remaining_time_entries << time_entry
      end   
    end
    remaining_time_entries
  end

  # calculate total hours, round to 2 decimal places
  def total_hours
    if (self.start != nil) && (self.end != nil)
      (((self.end - self.start) / 3600) * 10**2).round.to_f / 10**2
    else
      0.0 
    end
  end

  def year
    self.start.year
  end

  def date
    "#{Time::RFC2822_DAY_NAME[self.start.wday]}, #{Time::RFC2822_MONTH_NAME[self.start.month-1]} #{self.start.day} #{self.start.year}"
  end

  def to_s
    "\"#{self.comment}\" on #{self.date} for #{self.total_hours} hours"
  end
end

Now you can run the test again and we should now have a clean set of tests for TimeEntry. In the next installment we will tackle testing and creating the application controllers and finally get something that we can show our besides tests on the command line.

Posted in ,  | Tags , ,  | 2 comments | no trackbacks

Comments

  1. rafael said 26 days later:

    Thanks for this it has been helpful.

    2 things.

    1. Are you going to finish this? It has been awhile since an update.

    2. Everything was going great until the end. The TimeEntry “should be invalid without an associated Project Activity” part to be specific. I followed instructions but I was unable to pass the final test. Would it be possible to download the sample code from somewhere?

    Ok, I know I said 2 things but … when running the test toward the end of the month and testing “should know how to split a time entry across multiple days” it fails if the test crosses a month barrier.

    Thanks again.

  2. Brian said 29 days later:

    Rafael, Thanks for the bug report. I will add a test that confirms your report and then refactor the code to pass the test

    Brian

Trackbacks

Use the following link to trackback from your own site:
http://www.integrallis.com/blog/trackbacks?article_id=building-tempo-with-rails-part-iii&day=31&month=10&year=2007

Comments are disabled

Tags

agile drools gorm Grails Groovy Java orm Rails Ruby Security spring

Categories

Archives

Syndicate

Twitter