fujimura
fujimura
2015/12/03 18:59:46 投稿
2

【Refactor Me】viewに条件式 のテストを書いてリファクタリング

殴り書きだし、そんなに良くなってない気もしますが、テストを書いたので投稿します!
他のリファクタリング案を書くときにコピペしてご活用ください。

  • ヘルパーに入れた
  • 安全になった
  • 分岐してる部分を減らした

https://github.com/fujimura/forkwell-refactorings-20

Before

# view
<% if current_user.admin? %>
  <%= current_user.message_for_admin(@message) %>
<% else %>
  <%= current_user.message_for_general(@message) %>
<% end %>

# app/models/user.rb
def message_for_admin message
  img_tag = '<img src="/assets/message/admin.png" />'
  span_tag = "<span>#{message.body}</span>"
  "<div>#{img_tag}#{span_tag}</div>"
end

def messsage_for_general message
  img_tag = '<img src="/assets/message/general.png" />'
  span_tag = "<span>#{message.body}</span>"
  "<div>#{img_tag}#{span_tag}</div>"
end

After

require 'erb'
require 'ostruct'
require 'test/unit'
require 'action_view'

class User
  def initialize(role = :admin)
    @role = role
  end

  def admin?
    @role == :admin
  end
end

module ViewHelper
  include ActionView::Helpers::TagHelper
  def message_by_user_role user, message
    src = if user.admin?
            "/assets/message/admin.png"
          else
            "/assets/message/general.png"
          end

    content_tag(:div, tag(:img, src: src) + content_tag(:span, message.body))
  end
end

ERB_TEMPLATE = DATA.read

class MyTest < Test::Unit::TestCase
  include ViewHelper

  def test_admin
    current_user = User.new :admin
    @message = OpenStruct.new(body: "This is admin")

    actual = ERB.new(ERB_TEMPLATE).result(binding).strip
    expected = %(<div><img src="/assets/message/admin.png" /><span>This is admin</span></div>)

    assert_equal(actual, expected)
  end

  def test_general
    current_user = User.new :general
    @message = OpenStruct.new(body: "This is general")

    actual = ERB.new(ERB_TEMPLATE).result(binding).strip
    expected = %(<div><img src="/assets/message/general.png" /><span>This is general</span></div>)

    assert_equal(actual, expected)
  end
end

__END__
<%= message_by_user_role(current_user, @message) %>

みんなのコメント