原创作者: hideto   阅读:920次   评论:0条   更新时间:2011-05-26    
继续重构。

我们先来写User类的单元测试,定义3个测试方法:
require File.dirname(__FILE__) + '/../test_helper'

class UserTest < Test::Unit::TestCase
  fixtures :users

  def test_full_name_without_middle_initial
    user = User.new(:first_name => 'John', :last_name => 'Doe')
    assert_equal 'John Doe', user.full_name
  end

  def test_full_name_with_middle_initial
    user = User.new(:first_name => 'John', :middle_initial => 'H', :last_name => 'Doe')
    assert_equal 'John H. Doe', user.full_name
  end

  def test_full_name_with_blank_middle_initial
    user = User.new(:first_name => 'John', :middle_initial => '', :last_name => 'Doe')
    assert_equal 'John Doe', user.full_name
  end
end

我们再看看我们的full_name方法,显然是无法满足所有的测试的:
class User < ActiveRecord::Base
  def full_name
    name = first_name
    name += "#{middle_initial}." unless middle_initial.nil?
    name += last_name
    name
  end
end

而且middle_initial后面跟一个"."也让我们的代码"风水"不好,比如我们突然有一天把"."改成"-"呢?好,我们继续重构吧:
class User < ActiveRecord::Base
  def full_name
    [first_name, middle_initial_with_period, last_name].compact.join(' ')
  end

  def middle_initial_with_period
    "#{middle_initial}." unless middle_initial.blank?
  end
end

运行测试,ok,通过了!
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics