0

There is a private method with the following code.

attr_reader :some_variable

validate :some_def

def some_def
  unless some_variable.valid?
    some_variable.errors.messages.each do |message|
      errors.add(:some_variable, message)
  end
end

I am new to rspec and not familiar with private method testing. Any help is appreciated.

I need to cover the lines of the private method.

Chintu Karthi
  • 137
  • 2
  • 12
  • It looks like validation testing - https://makandracards.com/makandra/38645-testing-activerecord-validations-with-rspec – MrShemek Mar 29 '19 at 11:38
  • Hi, I already went through the link, but am not able to understand that. If you could please explain how. Thanks. – Chintu Karthi Mar 29 '19 at 11:55
  • IMO you can: initialize the object, set `some_variable` value as invalid and then call `valid?` on the object you initialized (it should return `false`). Then, repeat the same but set the correct value for `some_variable` and check if you get `true` when calling `valid?` – MrShemek Mar 29 '19 at 13:15
  • Writing test for private method is not a good practice. Checkout interesting post https://stackoverflow.com/a/105021/398863 – Amit Patel Mar 30 '19 at 18:36

1 Answers1

0

you can do something like this:

describe 'validations' do
  let(:some_variable_object) { SomeVariable.new } 
  let(:new_foo) { described_class.new(some_variable: some_variable_object) }

  context 'when some_variable is valid' do
    before do
      allow(some_variable_object).to receive(:valid?) { true }
    end

    it 'is valid' do
     expect(new_foo).to be_valid
    end

    it 'does not have errors related to some_variable' do
      expect(new_foo.errors[:some_variables]).to be_empty
    end
  end

then you can do the same to test the opposite, when some_variable is not valid... now, there are tools to help you setting up objects within the spec easily (FactoryBot).

mr_sudaca
  • 1,156
  • 7
  • 9
  • What does `SomeVariable` here `let(:some_variable_object) { SomeVariable.new } ` means? like the same instance variable? if so if it was capitalized, it will through uninitialized error right? – Chintu Karthi Mar 30 '19 at 17:02