Ruby on rails Rspec expect方法接收ActiveRecord::Relation
我有办法Ruby on rails Rspec expect方法接收ActiveRecord::Relation,ruby-on-rails,ruby,activerecord,rspec,Ruby On Rails,Ruby,Activerecord,Rspec,我有办法 foo(条形) 条是一种ActiveRecord::关系 在我的规范中,我想断言foo是用bar调用的,但是在规范中bar只是一个数组 let(:bar) { create(:bar) } let(:bars) { [bar] } expect(described_class).to receive(:foo).with(bars) 有没有办法做到这一点?我无法在控制器中存根条,因为我正在根据通过的参数测试对条的过滤。您可以检查条是否为您期望的值,而不是伪造条: expect(de
foo(条形)
条
是一种ActiveRecord::关系
在我的规范中,我想断言foo
是用bar
调用的,但是在规范中bar
只是一个数组
let(:bar) { create(:bar) }
let(:bars) { [bar] }
expect(described_class).to receive(:foo).with(bars)
有没有办法做到这一点?我无法在控制器中存根
条
,因为我正在根据通过的参数测试对条
的过滤。您可以检查条是否为您期望的值,而不是伪造条:
expect(described_class).to receive(:foo) do |bars|
# verify bars here. You could do bars.to_a and check the array
# or bars.to_sql and check the generated sql.
end
您可以对某些东西设置期望值,但仍然让它运行原始代码。只需将和_call_original
添加到您的期望中:
expect(described_class).to receive(:foo).with(bars).and_call_original
这里提供的文档中的详细信息:我尝试了类似于let(:bar){BarClass.where(id:[bar.id])}
的方法,因此预期的bar
也是ActiveRecord::Relation
。但由于ActiveRecord::Relation#=
方法,它没有工作。我的预期的
与实际的
具有不同的SQL
From: gems/activerecord-6.0.2.1/lib/active_record/relation.rb @ line 682:
Owner: ActiveRecord::Relation
Visibility: public
Number of lines: 10
def ==(other)
case other
when Associations::CollectionProxy, AssociationRelation
self == other.records
when Relation
other.to_sql == to_sql
when Array
records == other
end
end
但在RSPEC代码中搜索时,我发现,.with()
接受块。不是直接接收,而是在receive
上接收。正如@Jeff F.已经写的那样
因为我需要export
方法上的存根返回值,所以它的结尾都是:
exporter_double = instance_double(Xml::Exporter::InventoriesExporter, export: "<xml>Result of export to POHODA for [#{inventories.collect(&:code).join(',')}]</xml>")
expect(Xml::Exporter::InventoriesExporter).to receive(:new) do |arg1, arg2, arg3|
# doing my own `.with(inventories, :xml, {})` because actual `inventories` is ActiveRecord::Relation, not array
expect(arg1.to_a).to eq(inventories)
expect(arg2).to be(:xml)
expect(arg3).to eq({})
end.and_return(exporter_double)
exporter\u double=instance\u double(Xml::exporter::inventoriesporter,export:“[#{inventory.collect(&:code.join(',')}]”导出到POHODA的结果)
期望(Xml::Exporter::InventoriesPorter).接收(:新建)do | arg1、arg2、arg3|
#使用(inventory,:xml,{})执行我自己的`.with`,因为实际的` inventory`是ActiveRecord::Relation,而不是数组
预期(arg1.至a.至等式(存货)
expect(arg2).be(:xml)
expect(arg3).to eq({})
结束和返回(出口商双)