Tashi Dendup
Tashi Dendup

Reputation: 359

Rspec model testing 'validate_presence_of' throws Module::DelegationError

This is my specs

describe 'Do sth..' do
  it { should validate_presence_of :some_attribute }    
end

In my model I have But I am getting

class Order < ApplicationRecord
  has_one :sub_order, inverse_of: :order, dependent: :destroy

  validates_presence_of :some_attribute

  delegate(
    :some_attributes1,
    to: :sub_order
  )
end

Module::DelegationError: Order#some_attributes1 delegated to sub_order.some_attributes1, but sub_order is nil: #

Can any help me please? Thanks in advance!

Upvotes: 1

Views: 626

Answers (1)

mrzasa
mrzasa

Reputation: 23347

Just as the error says: sub_order is nil so method call cannot be delegated there. You have two options:

  1. Ensure that sub_order is not nil (e.g. by overriding the getter)
  2. Use .delegate with :allow_nil option

:allow_nil - if set to true, prevents a Module::DelegationError from being raised

https://api.rubyonrails.org/classes/Module.html#method-i-delegate

Upvotes: 2

Related Questions