FactoryBot難しい...
ジョブを実行すると、ある条件の時にレコードが更新されることをテストしたかったのですが、なかなかテストが通らないため、binding.pryを駆使してデバックしておりました。
しかし、binding.pryだときちんと値が更新されているのに、なぜかテストは落ちておりました。
そこで p メソッドでFactoryBotでつくったオブジェクトと、後からfind_byで検索したオブジェクトを出力してみたところ、同じものだと思っていたオブジェクトが別物であることがわかりました!
(テストじゃない場合は同じレコードになる)
以下はそのテストコードです。
require "rails_helper"
RSpec.describe InvoiceCloseJob, :type => :job do
include ActiveJob::TestHelper
略
let!(:contract_auto_before_closing_day) { FactoryBot.create(:contract, :auto_before_closing_day) }
略
describe "契約期間延長処理" do
略
context "自動延長有効の契約書" do
context "契約期間終了日 < 締め期間の最終日" do
it "契約期間が更新されること" do
InvoiceCloseJob.perform_now(invoice_close)
p contract_auto_before_closing_day
p Contract.find_by(display_name: 'auto_before_closing_day')
expect(contract_auto_before_closing_day.to).to_not eq("2019-04-29".to_date)
end
end
略
こちらはターミナルに出力されたオブジェクトです。
idが別物でした。
そして、find_byで検索してきた方のオブジェクトはきちんと値が更新されておりました。
#<Contract id: 511, client_id: 2, from: "2019-04-01", to: "2019-04-29", billing_closing_date_id: 1, contract_type: "従量課金制", status: "actived", display_name: "auto_before_closing_day", created_at: "2019-06-12 05:09:46", updated_at: "2019-06-12 05:09:46", service_id: 2, display_name_service: "", auto_extension: true, extension_months: 6, ceil_digit: nil, had_spot_item: false>
#<Contract id: 467, client_id: 2, from: "2019-04-30", to: "2019-10-29", billing_closing_date_id: 1, contract_type: "従量課金制", status: "actived", display_name: "auto_before_closing_day", created_at: "2019-06-12 04:32:07", updated_at: "2019-06-12 05:09:49", service_id: 2, display_name_service: "", auto_extension: true, extension_months: 6, ceil_digit: nil, had_spot_item: false>
無事、expect( ) の引数をfind_byで引っ張ってきた方のオブジェクトに変更したところ、テストが通ってくれました。
FactoryBot難しい。。。