【问题标题】:Testing association validations with RSpec and FactoryGirl使用 RSpec 和 FactoryGirl 测试关联验证
【发布时间】:2014-04-25 13:14:42
【问题描述】:

我目前正在尝试为验证方法编写 RSpec 测试。此方法在记录更新、保存或创建时触发。这是我目前所拥有的:

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 方法中可以看出,当 single 属性设置为 true 并且产品具有多个关联的 SKU。但是,在运行测试时,产品没有关联的 SKU,因此无法通过上面显示的单元测试。

如何在 FactoryGirl 中创建记录并生成可以计数和验证的相关 SKU(例如:product.skus.count)?

【问题讨论】:

    标签: ruby-on-rails ruby unit-testing rspec factory-bot


    【解决方案1】:

    你可以这样写

      it 'should raise an error' do
        product = build(:product_skus, single: true)
    
        expect(product).not_to be_valid
      end
    

    【讨论】:

    • to downvoter:您可以使用 not_to 或 to_not。一个是另一个的别名!所以,不,这不是错误的语法!
    猜你喜欢
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多