首页 > 解决方案 > 检查 rspec 测试中的 WHERE CLAUSE 子句

问题描述

我在 Rails 中有一个命名范围,并且我有名称为 Product 的模型

class Product < ApplicationRecord
 scope :old_products, -> { where("tagged_with = ?","old") }
end

是否有任何机构遇到过检查在活动记录中使用 where 的主题的过程,并且可以检查命名范围实际包含的 where 子句

在 rspec spec/models/product_spec.rb

describe Product do
  describe "checking scope clauses" do
  subject { Product.old_products }
    its(:where_clauses)   { should eq([
      "tagged_with = 'old'"
    ]) }
  end
  end
end

顺便说一句,我使用 rspec-2.89 版本和 rails-5 版本,所以我们有机会检查和验证 where 子句

标签: ruby-on-railsrspec

解决方案


我个人认为检查范围的返回 SQL 是不够的。我要测试的方式old_products是:

describe Product do
  describe "scopes" do
    describe "old_products" do
      let!(:old_product) {Product.create(tagged_with: 'old')}
      let!(:not_old_product) {Product.create(tagged_with: 'sth_else')}
      subject { Product.old_products }

      it "returns the product(s) with tagged_with = old" do
        expect(subject).to eq([old_product])
      end
    end
  end
end

如果您仍然想检查返回查询,可能想尝试:

it "..." do
  expect(subject.to_sql).to eq("SELECT \"products\".* FROM \"products\" WHERE \"products\".\"tagged_with\" = 'old'")
end

推荐阅读