RSpec:工厂bot定义文件中的方法存根

时间:2019-03-29 17:48:52

标签: ruby-on-rails rspec factory-bot attr-encrypted

我有一个模型,该模型使用CREATE OR REPLACE TYPE Cuenta_udt; / CREATE OR REPLACE TYPE cuentas_array AS TABLE OF REF Cuenta_udt; / CREATE OR REPLACE TYPE Cliente_udt AS OBJECT ( DNI VARCHAR(9), Telefono NUMBER, Direccion VARCHAR(100), Email VARCHAR(50), Edad NUMBER, Apellidos VARCHAR(40), Nombre VARCHAR(30), Cuentas cuentas_array) FINAL; / CREATE TABLE Cliente OF Cliente_udt( DNI PRIMARY KEY, Telefono NOT NULL, Direccion NOT NULL, Edad NOT NULL, Apellidos NOT NULL, Nombre NOT NULL ) OBJECT IDENTIFIER IS SYSTEM GENERATED NESTED TABLE Cuentas STORE AS Cuentas_tab; / CREATE OR REPLACE TYPE clientes_array AS TABLE OF REF Cliente_udt; / CREATE OR REPLACE TYPE Cuenta_udt AS OBJECT ( IBAN VARCHAR(28), Saldo FLOAT, Numero_de_cuenta NUMBER, Fecha_creacion DATE, Clientes clientes_array ) NOT INSTANTIABLE NOT FINAL; / CREATE TABLE Cuenta OF Cuenta_udt ( IBAN PRIMARY KEY, Saldo NOT NULL, Numero_de_cuenta NOT NULL, Fecha_creacion NOT NULL ) OBJECT IDENTIFIER IS SYSTEM GENERATED NESTED TABLE Clientes STORE AS Clientes_tab; gem加密密码。

    for i in range(len(testLabels)):
        result_file = open('filePath.csv', 'a')
        result_file.write("{}{}".format(testLabels[i], '\n'))

我正在学习编写测试用例,而我的工厂看起来像这样:

attr_encrypted

我的规格文件如下:

class Credential < ApplicationRecord
  validates :user_name, presence: true
  enum credential_type: { windows: 1, linux: 2 }

  attr_encrypted :user_pass, key: :encryption_key

  def encryption_key
    # Some complex logic
  end
end

如何在工厂定义中对FactoryBot.define do factory :credential do user_name { "rmishra" } user_pass { "secret" } credential_type { "linux" } encryption_key { "abcdefghijklmnopqrstuvw123456789" } end end 方法进行存根,该方法在RSpec.describe Credential, type: :model do let(:credential) { create(:credential) } ... end 时就开始使用?

1 个答案:

答案 0 :(得分:0)

由于encryption_key不是模型的属性,因此无法在工厂中对其进行配置。

encryption_key分配给attr_encrypted对象时,user_pass宝石会自动调用

Credential。在这种情况下,这是由工厂完成的。

我会将您的encryption_key方法中的逻辑移到一个类中以方便测试:

class Credential < ApplicationRecord
  validates :user_name, presence: true
  enum credential_type: { windows: 1, linux: 2 }

  attr_encrypted :user_pass, key: :encryption_key

  def encryption_key
    EncryptionKeyGenerator.generate # or whatever name makes more sense
  end
end

然后,在我的测试中,我将对EncryptionKeyGenerator进行存根:

RSpec.describe Credential, type: :model do
  let(:credential) { create(:credential) }
  let(:encryption_key) { "abcdefghijklmnopqrstuvw123456789" }

  before do
    allow(EncryptionKeyGenerator).to receive(:generate).and_return(encryption_key)
  end

  ...
end

将加密密钥生成逻辑封装到一个单独的对象中,可以将其与模型分离,从而无需创建Credential对象即可轻松测试该逻辑。