我有一个看起来像这样的类:
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 关联进行 stub ,但允许 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 正确执行?
谢谢!
最佳答案
对于 RSpec 2.14.1(它也应该适用于 RSpec 3.1),我会试试这个:
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: "讨厌”
。它可以在未来的 bar 模拟中重复使用(至少对于返回单个实例,对于多个实例,您将添加另一个 double)。
关于ruby-on-rails - 如何 stub 事件记录关系以使用 rspec 测试 where 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26763398/