0
我正在尝试为验证方法编写RSpec测试。记录更新,保存或创建时会触发此方法。以下是我迄今为止:使用RSpec和FactoryGirl测试关联验证
product.rb(模型)
class Product < ActiveRecord::Base
validate :single_product
# Detects if a product has more than one SKU when attempting to set the single product field as true
# The sku association needs to map an attribute block in order to count the number of records successfully
# The standard self.skus.count is performed using the record ID, which none of the SKUs currently have
#
# @return [boolean]
def single_product
if self.single && self.skus.map { |s| s.active }.count > 1
errors.add(:single, " product cannot be set if the product has more than one SKU.")
return false
end
end
end
products.rb(FactoryGirl测试数据)
FactoryGirl.define do
factory :product do
sequence(:name) { |n| "#{Faker::Lorem.word}#{Faker::Lorem.characters(8)}#{n}" }
meta_description { Faker::Lorem.characters(10) }
short_description { Faker::Lorem.characters(15) }
description { Faker::Lorem.characters(20) }
sku { Faker::Lorem.characters(5) }
sequence(:part_number) { |n| "GA#{n}" }
featured false
active false
sequence(:weighting) { |n| n }
single false
association :category
factory :product_skus do
after(:build) do |product, evaluator|
build_list(:sku, 3, product: product)
end
end
end
end
product_spec.rb(单位测试)
require 'spec_helper'
describe Product do
describe "Setting a product as a single product" do
let!(:product) { build(:product_skus, single: true) }
context "when the product has more than one SKU" do
it "should raise an error" do
expect(product).to have(1).errors_on(:single)
end
end
end
end
从singe_product方法中可以看出,当单个属性设置为true并且产品具有多个关联的SKU时,我试图在单个属性上触发错误。但是,在运行测试时,产品没有关联的SKU,因此上述单元测试失败。
如何在FactoryGirl中创建一个记录并生成相关的SKU(可以计算在内)(例如:product.skus.count)并进行验证?
到downvoter:您可以not_to或to_not使用。一个是另一个的别名!所以,不,这不是一个不正确的语法! – Danny