15

I have a private method that I am trying to use #send to in Ruby to do some testing. The method is complicated and I don't want exposed outside of the class and so I want to test the method but I also don't need to list it as a public method. It has keyword arguments. How can I use send to call the method but also pass it keyword arguments/named parameters? Is there a way?

The method looks like this:

def some_method(keyword_arg1:, keyword_arg2:, keyword_arg3: nil)

1 Answer 1

32

Depends on how the keyword args are defined.

If they're defined inline for whatever reason, pass them inline:

SomeClass.send(:some_method, {keyword_arg1: 'foo', keyword_arg2: 'bar'})

If they're defined in a hash, you can unpack it instead:

hash = {keyword_arg1: 'baz', keyword_arg2: 'bing'}
SomeClass.send(:some_method, **hash)
Sign up to request clarification or add additional context in comments.

1 Comment

Note that in Ruby 3.0 you MUST use the double splat operator. obj.send(:some_method, **{arg1: 'foo', arg2: 'bar'})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.