如何在RSpec中测试before_validation回调模型问题

时间:2019-06-27 13:27:18

标签: ruby-on-rails rspec rspec-rails shoulda rspec-expectations

我正在学习为代码编写规范,但我仍然是新手。试图为我的Model编写规格说明/ SharedExamples,但是我不知道如何编写它,因为我发现这很复杂。

如果有人可以帮助我或向我展示如何为此类代码编写规范,将非常有帮助。以下是我关注的AddStakeholder。

module AddStakeholder
  extend ActiveSupport::Concern

  included do
    before_validation -> { add_stakeholders }
  end

  private

  def add_stakeholders
    return unless self.stakeholder

    company = if self.is_a?(Certificate)
                self.round ? self.round.company : self.company
              else
                self.company
              end
    existing_stakeholder = company.stakeholders.find_by_email(self.stakeholder.email)
    if existing_stakeholder.present?
      if self.stakeholder.name == existing_stakeholder.name
        self.stakeholder = existing_stakeholder
      else
        self.stakeholder.company = company
      end
    else
      self.stakeholder.company = company
    end
  end
end

1 个答案:

答案 0 :(得分:0)

您的代码段中没有足够的信息来准备完整的示例,但是看起来与以下内容类似:

RSpec.describe Thing, type: :model do
  it "adds stakeholders" do
    t = Thing.new(...)
    expect(t).to be_valid # or .to_not be_valid depending on your validations on Thing
    expect(t.stakeholder).to ... # whatever you expect it to be
  end
end