確認作業
Bin/rspec #だけだと全部になっちゃって重くなる
#コントローラも含んじゃうかも,重くなる
bin/rspec spec/*/admin_user_spec.rb
#モデルだけ
bin/rspec spec/models/admin_user_spec.rb
#6行目のテストだけ確認
bin/rspec spec/models/admin_user_spec.rb:6
subjectの位置
Contextの中に subject{}書いても反映されない、エラーになる
スコープ
describe 'メソッド動作テスト' do
context 'set_company_for_user' do
subject { FactoryBot.create(:pre_order) }
it 'userに紐付くcompanyに紐づけられること' do
expect(subject.company).to eq subject.user.company
end
end
before :all do
@company = FactoryBot.create(:company)
@shop = FactoryBot.create(:shop, company: @company)
@user = FactoryBot.create(:user , shop: @shop)
@sps_user = FactoryBot.create(:sps_user, user: @user)
@cart = FactoryBot.create(:cart, user: @sps_user.user , created_at: 1.day.ago, shop_id: @shop.id)
@pre_order = PreOrder.create_from_cart(@cart)
end
context 'create_from_cart' do
it 'カートが正しくDBに作られる' do
expect(@pre_order).to be_truthy
end
end
context 'create_reserve_from_cart' do
it '事前予約が正しくDBに作られる' do
cart = FactoryBot.create(:cart, user: @sps_user.user, shop: @sps_user.user.shop)
product = FactoryBot.create(:product, shop: cart.user.shop)
cart.add_or_update(product , 1)
pre_order = PreOrder.create_reserve_from_cart(cart, 1.day.since, 1.day.since)
expect(pre_order).to be_truthy
end
end
before :all do
のスコープは1回しかまわらないから、it
内で使うとするなら変数名の前に@
をつける必要がある
データ削除
context 'created_at' do
before :all do
⭐️ PreOrder.destroy_all
FactoryBot.create(:pre_order, created_at: Date.today.beginning_of_day)
FactoryBot.create(:pre_order, created_at: Date.today.end_of_day)
end
it 'created_atは指定された日付の間の時間' do
params = {}
params[:created_at] = Date.today.strftime('%Y-%m-%d')
expect(PreOrder.search(PreOrder, params).count).to be 2
end
end
FactoryBotで作成したデータが残っているせいで、count
の値が想定している値と一致しない!
そんな時は、PreOrder.destroy_all
モデルのデータを全削除すれば、ここれ作ったFactoryBot2件の世界でテストできる