【问题标题】:rspec service objects how to test update_allrspec 服务对象如何测试 update_all
【发布时间】:2020-06-22 12:11:03
【问题描述】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 非常感谢!你能解释一下什么是重载吗?
    • 它从数据库中重新加载该对象的属性。服务调用使测试中的对象副本过时,因此您需要从数据库中重新加载属性。
    猜你喜欢
    • 2017-10-20
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多