ruby-on-rails - 如何 stub 事件记录关系以使用 rspec 测试 where 子句?

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

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

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/

相关文章:

ruby - 如何在没有其他任何东西的情况下运行多个 Sinatra 实例?

Python 相当于 Ruby 的表达式 : "puts x += value"

ruby - Rake 的目的是什么?

scala - Scala 对象(非类)的单元测试

javascript - 在关于 expect.throw 的链中进行单元测试时遇到问题

ruby-on-rails - 如何将字符串拆分为键值对?

ruby-on-rails - 在 Rails 3.1 中重新加载 lib 文件而不重启开发服务器

ruby-on-rails - 在 Savon gem 中使用带参数的多个参数

ruby-on-rails - 如何在 Action Mailer 中指定发件人姓名

android - Schedulers.immediate() 不适用于命令行 gradle 测试