ruby-on-rails - 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
解决方案
对于此服务,您显然对副作用更感兴趣,而不是返回值,因此在规范中描述您期望的测试状态,例如:
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
推荐阅读
- vba - 如何在 Powerpoint 中获取录制声音的长度
- java - 如何在Java中对泰语字符串数组进行排序
- html - CSS - 平滑扩展按钮宽度并在悬停时显示文本
- jenkins - SONAR 与 Jenkins 的集成。错误:您无权运行分析。请联系项目管理员
- android - 位图在Android中减少高度和宽度
- python - 属性错误模块“时间”没有属性“时钟”(pyqt5)
- javascript - 如何在 d3 version4 的原始源中添加 y0 和 y1 值?
- camunda - 将变量传递给 url 从服务任务到另一个
- python - 如何有效地将 Python 结构转换为 serde_json::Value?
- java - 跨多个语句的相同时间戳