1

Help! I'm in a fix .. check it:

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

I'm trying to figure out how to:

  1. Trigger a callback after the :user has been created, but before the :card has been created (or the Model validations will fail since the card isn't encrypted)

  2. Make the :unencrypted trait override the callback above.

FloatingRock
  • 6,741
  • 6
  • 42
  • 75

1 Answers1

1

The trick mentioned in this answer and this issue is to change the create method to save without validating. Then, you can add an after(:create) that encrypts the value.

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

Also note that "if the factory name is the same as the association name, the factory name can be left out."

Community
  • 1
  • 1
Dan Kohn
  • 33,811
  • 9
  • 84
  • 100