Everyday Rails - 13日目 前半

10. その他のテスト rakeタスクをテストする

rakeタスクファイルにモリモリ書くのではなく、ビジネスロジックを担当するクラスを作成し、そこに閉じ込めちゃいましょう、という話。
そうすることでテスタビリティが向上します、ということ。

  • personモデル作成
$ ./bin/rails g model Person firstname lastname email
  • lib/legacy.rb

Phoneが必要なのだが、本題と外れるのでとりあえず空で入れておく。

class Legacy
  def self.move_people
    Person.all.each do |person|
      Contact.create(
        firstname: person.firstname,
        lastname: person.lastname,
        email: person.email,
        phones: Array.new(3) { Phone.new }
      )
    end
  end
end
  • config/initializers/require_libs.rb
require 'legacy'
  • spec/lib/legacy_spec.rb

こういう場合のテストの書き方ってどうやるんだろう。
別々に分けるのもどうかと思うし、過剰かもしれないし。

require 'rails_helper'

describe Legacy, type: :model do
  before do
    @people = create_list(:person, 5)
  end

  it 'creates a contact from a person' do
    expect {
      Legacy.move_people
    }.to change(Contact, :count).by(5)
    expect(Contact.pluck(:firstname)).to match_array(@people.map(&:firstname))
    expect(Contact.pluck(:lastname)).to match_array(@people.map(&:lastname))
    expect(Contact.pluck(:email)).to match_array(@people.map(&:email))
  end
end