ruby-on-rails - 检查 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 子句
解决方案
我个人认为检查范围的返回 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
推荐阅读
- r - 如何为 shapiro.test 创建一个循环
- laravel - Laravel 产品变体的深度关系
- visual-studio - VS 2017 如何确定来自 Paket 的 .NET Standard 依赖项?
- utf-8 - UUID 编码为 ascii 而不是 utf-8
- windows - 功能区将仅显示最小化
- java - 仅显示 3 行
标签包含几个
- python - Python Datetime strptime 不带年份,自动插入当前年份
- c# - 如何防止在条件为真时创建类的实例。C#
- android - 我从 Play 管理中心收到以下错误,我无法编辑版本或 Google Play 信息
- c++ - 模板接口返回类型