How to Test the Private Method of the Model

Asked 2 years ago, Updated 2 years ago, 112 views

model

class test
  def initialize(val1,val2)
    validate(val1,val2)
  end
  private 
  def validate(val1,val2)
    raise xxxx errorless val1.presnet?
    raise yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
  end
end

I want to test validate

General Writing

@test=Test.new(val1,val2)
@test.send(:validate,val1,val2)

→Validate runs twice?(when instance is generated and when run in send

)

Solution
①Stub new and return dummy instances of the Test class?
(I don't know how to use a dummy instance...)

他 Call the private method directly using other methods
(I don't know how to call...)

What do you want to hear

、 and どちらWhich one is better
①How do I return a dummy instance if
②In the case of
how exactly do you call them? I would like to know that

I'm sorry, but I'd appreciate it if you could let me know as a beginner.

ruby rspec test

2022-09-30 21:22

2 Answers

Basically, I don't think I will test the private method.

In this case, it would be better to test Test#initialize (this is also a private method, so Test.new).

expect {Test.new(...)}.to raise_error(xxxerror)


2022-09-30 21:22

You can use Class#allocate to ensure that only objects are secured without executing the initialize method.

@test=Test.allocate
@test.send(:validate,val1,val2)

If it's rspec,

expect {Test.allocate.send(:validate,val1,val2)}.to raise_error XXXXError

However, if there is a class from which to inherit it, initialize it will not be executed, and the test code can be complicated because it will be a really empty object.
If possible, the class should be designed not to write such tests.


2022-09-30 21:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.