rspec 服务对象如何测试 update_all

rspec service objects how to test update_all

我不明白,如何测试这个案例。我用谷歌搜索但没有找到任何东西。 结果(我认为我是正确的)我应该期望 return 2 个新状态为 false 的对象,因为我通过在 let 中创建的第一个对象传入 subject.call id。 请有人帮助我并向我解释如何测试 update_all 和其他更新案例。谢谢!

#rspec

describe Plans::MakeAllPlansInactive do
  subject do
    described_class.call(plan_id: plan.id)
  end

  let!(:plan) do
    create(:plan, active: true)
  end

  let!(:plan_1) do
    create(:plan, active: true)
  end

  let!(:plan_2) do
    create(:plan, active: true)
  end


  context 'when success' do
    it 'makes one active, other passive' do
      subject.to eq(2)
    end
  end

#服务

def call
  return unless Plan.find(plan_id).active?

  update_our_plans
end

private

def update_our_plans
  Plan.where.not(id: plan_id).update_all(active: false)
end

对于此服务,您显然对副作用比 return 值更感兴趣,因此在规范中描述您期望通过如下测试期望的状态:

it 'makes one active, other passive' do
  expect(Plan.count).to eq(3) # just to be sure
  expect{ subject }.to change{ plan_1.reload.active }.from(true).to(false).and(
    change{ plan_2.reload.active }.from(true).to(false)
  ).and(not_change{ plan.reload.active })
end