0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

暇なので毎日1つリファクタしてみるのも...あり?

Posted at

Overview

「暇なときはテストでいい感じにコードをリファクタしてみる」

Motivation/Context

最近暇なのですが、コードを書いてないとなんかむずむずします。
ということで、何かやることはないかな〜なんて思っていました。
そんな時に、いい暇つぶしを思いついたのでシェアしてみます。

Get Started!!

今回は、なんとなーく自作しているアプリのcontrollerにあった長ったらしい処理をmodelに移動させて、modelスペックを書いて見ました。
ついでに、最近覚えたてのFactorybotを使って見ました。

以降前のcontroller

@apply = Apply.new(
  user_id: current_user.id,
  location_id: @location.id,
  date: Date.today,
  time_start: Time.new(2024,1,1,12,0),
  time_end: Time.new(2024,1,1,13,0),
  message: "ああああああ"
)

以降後のcontroller

@apply = Apply.initilize_apply(current_user.id, @location.id)

移行後に追加したテスト系のファイル

describe "#initilize_apply" do
  it "正常に初期化される" do
    user = FactoryBot.create(:user)
    location = FactoryBot.create(:location)
    apply = Apply.initilize_apply(user.id, location.id)
    expect(apply).to be_valid
  end
end
FactoryBot.define do
  factory :location do
    title { "..." }
    catch_copy { "..." }
  end
end
FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "test_user_#{n}@example.com" }
    password { Devise::Encryptor.digest(User, 'password') }
    admin { false }
  end
end

インフォメーション
「初期化処理ならinitializeメソッドあんじゃん!」というツッコミはご遠慮くださいw
次回くらいのリファクタリングでやってみよって思います!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?