2

I'm trying to write a test where I need the value created by the expected block to write the assertion.

class Identification < ApplicationRecord
  include Wisper::Publisher

  after_save :publish_identification_declined

  private

  def publish_identification_declined
    if status_previously_changed? && status == "declined"
      broadcast(:identification_declined, identification: self)
    end
  end
end

I tried to do something like this but unfortunately identification_a ends up not being set.

require "rails_helper"

RSpec.describe Identification do
  it "publish event identification_declined" do
    identification_a = nil
    expect { identification_a = create(:identification, :declined, id: 1) }
      .to broadcast(:identification_declined, identification: identification_a)
  end
end

I also have a feeling that this might not be a good idea.

An alternative could be using the instance_of matcher but then I don't know how to check if it's the right instance.

TheVTM
  • 1,510
  • 13
  • 14

1 Answers1

-1

I think you shouldn't test the private functions because these are like black box and no matter how it works, as long as it returns as expected, obiously some times is necessary but in that case I think that the function shouldn't being private.

If you want test that the function is called, you can use receive rspec function. Some like:

require "rails_helper"

RSpec.describe Identification do
  subject { described_class.new(identification: nil, :declined, id: 1) }

  it "updates the state after save(or the event that should runs)" do
    expect { subject }.to receive(:publish_identification_declined)
    subject.save
  end
end

You also can see the the documentation