关联回调后

时间:2014-11-19 15:23:14

标签: ruby-on-rails factory-bot

帮助!我正在修理..检查一下:

FactoryGirl.define do
  factory :card do
    number "1234123412341234"
    exp_month 12
    exp_year 2016

    association :user

    before(:create) do |instance|
      # Start a crypto instance with this users public key and encrypt
      crypt = Modules::Crypto.new(instance.user.encryption_key_id)
      instance.number = crypt.encrypt("1234123412341234")
    end

    trait :unencrypted do
      number "1234123412341234"
    end
  end
end

我试图找出如何:

  1. 在创建:user之后触发回调,但之前 :card已创建(或模型验证)因为卡没有加密会失败)

  2. :unencrypted特征覆盖上面的回调。

1 个答案:

答案 0 :(得分:1)

answer和此issue中提到的技巧是将create方法更改为save而不进行验证。然后,您可以添加加密值的after(:create)

FactoryGirl.define do
  factory :card do
    to_create {|instance| instance.save(validate: false) }
    number "1234123412341234"
    exp_month 12
    exp_year 2016
    user

    after(:create) do |instance|
      # Start a crypto instance with this users public key and encrypt
      crypt = Modules::Crypto.new(instance.user.encryption_key_id)
      instance.number = crypt.encrypt("1234123412341234")
    end

    trait :unencrypted do
      number "1234123412341234"

      after(:create) do |instance|
        # This is a noop to override previous after(:create)
      end
    end
  end
end

另请注意,“如果工厂名称与关联名称相同,则可以省略工厂名称。”