【发布时间】:2018-06-01 19:28:44
【问题描述】:
我正在尝试为 spree 扩展(如 gem)中的自定义验证创建 rspec 测试
我需要验证 variants 的唯一性
option values 用于product(所有Spree 型号)
这是模型的基本结构(虽然它们是 spree 的一部分,一个基于 Rails 的电子商务建筑):
class Product
has_many :variants
has_many :option_values, through: :variants #defined in the spree extension, not in actual spree core
has_many :product_option_types
has_many :option_types, through: :product_option_types
end
class Variant
belongs_to :product, touch: true
has_many :option_values_variants
has_many :option_values, through: option_values
end
class OptionType
has_many :option_values
has_many :product_option_types
has_many :products, through: :product_option_types
end
class OptionValue
belongs_to :option_type
has_many :option_value_variants
has_many :variants, through: :option_value_variants
end
所以我创建了一个自定义验证来检查某个产品的变体选项值的唯一性。那是一个产品(比如说product1)可以有很多变体。并且具有选项值的变体可以说(Red(Option_type:Color)和Circle(Option_type:Shape))对于该产品必须是唯一的
无论如何这是自定义验证器
validate :uniqueness_of_option_values
def uniqueness_of_option_values
#The problem is in product.variants, When I use it the product.variants collection is returning be empty. And I don't get why.
product.variants.each do |v|
#This part inside the each block doesn't matter though for here.
variant_option_values = v.option_values.ids
this_option_values = option_values.collect(&:id)
matches_with_another_variant = (variant_option_values.length == this_option_values.length) && (variant_option_values - this_option_values).empty?
if !option_values.empty? && !(persisted? && v.id == id) && matches_with_another_variant
errors.add(:base, :already_created)
end
end
end
最后是规格
require 'spec_helper'
describe Spree::Variant do
let(:product) { FactoryBot.create(:product) }
let(:variant1) { FactoryBot.create(:variant, product: product) }
describe "#option_values" do
context "on create" do
before do
@variant2 = FactoryBot.create(:variant, product: product, option_values: variant1.option_values)
end
it "should validate that option values are unique for every variant" do
#This is the main test. This should return false according to my uniqueness validation. But its not since in the custom uniqueness validation method product.variants returns empty and hence its not going inside the each block.
puts @variant2.valid?
expect(true).to be true #just so that the test will pass. Not actually what I want to put here
end
end
end
end
任何人都知道这里出了什么问题。提前致谢
【问题讨论】:
-
我立即注意到您正在通过 let 设置
variant1,并设置@variant2但随后调用@variant.valid?但从未设置@variant。 -
@MarlinPierce.. 哦,我在这里写错了。我的意思是
@variant2而已。
标签: ruby-on-rails rspec spree