我有一个类,看起来像这样:
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测试来存根bars关联,但允许where自然执行。类似于:
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方法的错误。我该如何包装mock以便where能够适当地执行呢?
谢谢!