首页 > 解决方案 > rspec 服务对象如何测试 update_all

问题描述

我不明白,如何测试这种情况。我用谷歌搜索但没有找到任何东西。结果(我认为我是正确的)我应该期望返回 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

标签: ruby-on-railsrubyrspecrspec-rails

解决方案


对于此服务,您显然对副作用更感兴趣,而不是返回值,因此在规范中描述您期望的测试状态,例如:

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

推荐阅读