Jzr
Jzr

Reputation: 11

Rspec ask if a public methodo calls a private one ruby on rails

I'm trying to test if the public method create_file calls the private method get_users called in the private method add_product_data

class UsersXmlGenerator
  attr_reader :data

  def initialize(data)
    @data = data
  end

  def create_file
    builder = ::Builder::XmlMarkup.new indent: 2
    builder.instruct!

builder.products do |xml|
  data.each do |pa|
    add_product_data(pa, xml)
  end


   end
  end


  private

  def add_product_data(pa, xml)
    xml.product_application do |xml|
      xml.users do |xml|
        get_users(pa).each do |user|
          xml.user do |xml|
            sections_for_user(user).each do |section|
              section.add_xml(xml)
            end
          end
        end
      end
    end
  end

  def get_users(pa)
    pa.users.order_by_user.select(&:set_data?)
  end
end

Upvotes: 0

Views: 77

Answers (1)

spickermann
spickermann

Reputation: 106952

I would argue that testing a specific implementation detail is an anti-pattern and absolutely useless. There is no benefit in having a failing test after a refactoring as long as the result is still correct.

Apart from that, I would do the following to test if a specific method is called:

subject(:generator) { UsersXmlGenerator.new(data) }

before do
  allow(generator).to receive(:add_product_data).and_return_original
end

it 'calls `add_product_data`' do
  generator.create_file
  expect(generator).to have_received(:add_product_data)
end

Upvotes: 7

Related Questions