【问题标题】:How to stub an active record relation to test a where clause with rspec?如何存根活动记录关系以使用 rspec 测试 where 子句?
【发布时间】:2014-11-05 17:27:48
【问题描述】:

我有一个看起来像这样的类:

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 测试来存根条关联但允许自然执行的位置。比如:

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

上面的测试给出了一个关于数组没有方法的错误。如何包装模拟以便正确执行?

谢谢!

【问题讨论】:

  • 你使用的是什么版本的 RSpec?
  • 这个项目在 2.14.1 上,但我也有兴趣在最新版本上执行。

标签: ruby-on-rails ruby unit-testing rspec


【解决方案1】:

对于 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: "Nasty"的双标。它可以在以后的 bar 模拟中重复使用(至少对于返回单个实例,对于多个实例,您将添加另一个 double)。

【讨论】:

  • 不应该double('Bar')class_double('Bar') 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2018-01-16
  • 2021-04-13
  • 1970-01-01
相关资源
最近更新 更多