如何存根活动记录关系以使用 rspec 测试 where 子句? [英] How to stub an active record relation to test a where clause with rspec?
问题描述
我有一个看起来像这样的类:
I've got a class that look like this:
class Foo < ActiveRecrod::Base
has_many :bars
def nasty_bars_present?
bars.where(bar_type: "Nasty").any?
end
validate :validate_nasty_bars
def validate_nasty_bars
if nasty_bars_present?
errors.add(:base, :nasty_bars_present)
end
end
end
在测试#nasty_bars_present?我想编写一个 rspec 测试,该测试存根 bar 关联,但允许在何处自然执行.类似的东西:
In testing the #nasty_bars_present? I'd method like to write an rspec test that stubs the bars association but allows the where to execute naturally. Something like:
describe "#nasty_bars_present?" do
context "with nasty bars" do
before { foo.stub(:bars).and_return([mock(Bar, bar_type: "Nasty")]) }
it "should return true" do
expect(foo.nasty_bars_present?).to be_true
end
end
end
上面的测试给出了一个关于没有方法 where 数组的错误.我如何包装模拟以便在何处正确执行?
The test above gives an error about there being no method where for an array. How can I wrap the mock so the where will execute appropriately?
谢谢!
推荐答案
对于 RSpec 2.14.1(它应该也适用于 RSpec 3.1),我会试试这个:
For RSpec 2.14.1 (it should also work for RSpec 3.1), I would try this:
describe "#nasty_bars_present?" do
context "with nasty bars" do
before :each do
foo = Foo.new
bar = double("Bar")
allow(bar).to receive(:where).with({bar_type: "Nasty"}).and_return([double("Bar", bar_type: "Nasty")])
allow(foo).to receive(:bars).and_return(bar)
end
it "should return true" do
expect(foo.nasty_bars_present?).to be_true
end
end
end
这样,如果你调用 bars.where(bar_type: "Nasty")
而没有 where 语句中的特定条件,你将不会得到带有 bar_type: "讨厌"
.它可以重复用于未来的条形模拟(至少对于返回单个实例,对于多个实例,您将添加另一个双精度).
This way, if you call bars.where(bar_type: "Nasty")
without the specific conditions in the where statement, you won't get the bar double with bar_type: "Nasty"
. It could be reusable for future mocking of bars (at least for returning a single instance, for multiple instances, you would add another double).
这篇关于如何存根活动记录关系以使用 rspec 测试 where 子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!