Search code examples
ruby-on-railsfactory-botruby-on-rails-6attr-encrypted

In Rails 6 / FactoryBot 6, how do I simulate attr_encrypted attributes?


Recently upgraded to Rails 6 and FactoryBot 6.2.0. I have this model

class Store < ApplicationRecord

    …
  attr_encrypted :ein_number,
    key: APP_CONFIG[:app_encryption][::Rails.env][‘secret_key’]

I have corresponding factory

FactoryBot.define do
  factory :store do
    name                          { "Test Store” }
    …
    ein_number                 { "00-0000000" }

But now when I go and create an instance of this factory, I get the error

  Failure/Error: @store = create :store
  
  NoMethodError:
    undefined method `encrypted_ein_number_iv' for #<Store:0x00007feec319fbe0>

Not sure what changed in either Rails or FactoryBot but this worked before without my defining such a method. Seems like sort of a hack anyway. Is there a more elegant way to define this attribute in a factory?


Solution

  • Curiously, updating my attr_encryptor on my model to

      attr_encrypted :ein_number,
        key: APP_CONFIG[:cfs_encryption][::Rails.env]['secret_key'],
        algorithm: 'aes-256-cbc', mode: :single_iv_and_salt, insecure_mode: true
    

    solved the problem (factory created an instance of the object as normal).