這邊以之前的 use case 當作例子來撰寫測試。
首先要能快速地建立測資,需要透過 Factory Bot 制定規則。
# order_factory.rb
FactoryBot.define do
factory :entity_order, class: 'OrderEntity' do
serial_number { 'ABC-123456789' }
status { :successed }
puchased_at { Time.zone.now }
comment { nil }
skip_create
initialize_with { new(attributes) }
end
end
接著因為底層使用 Boxenn::Repository
,很好抽換。
# create_order_spec.rb
# 因為 use case 沒有用到 rails 因此不需要 require rails_helper
require 'lite_helper'
require 'timecop'
RSpec.describe CreateOrder do
describe '建立訂單' do
subject(:result) do
described_class.new(repo: order_repo).call(params: params)
end
let(:order_repo) { instance_double('OrderRepository'), save: true }
let(:params) {{ serial_number: 'XYZ-987654321', status: :successed, puchased_at: Time.zone.today, comment: '測試' }}
# 因為測試有時間性,因此利用 timecop 凍結時間
before(:example) do
Timecop.freeze(Time.zone.now)
end
after(:example) do
Timecop.return
end
# 需要安裝 wisper-rspec 才可以測 pub-sub
it '發布 event' do
expect { result }.to publish(:order_created)
end
it '新建訂單' do
expect(result.success?).to be_true
expect(order_repo).to have_received(:save) do |order|
expect(order.to_h).to include(expected_order.to_h)
end
end
end
def expected_order
create(
:entity_order,
serial_number: 'XYZ-987654321',
status: :successed ,
puchased_at: Time.zone.today,
comment: '測試',
)
end
end
下一篇會來聊聊 Boxenn::UseCase
遇到的問題。