15
15

More than 5 years have passed since last update.

RSpecでプライベートメソッドをテストする

Posted at

send を使用するのもいいが、以下のコードを RSpec ファイルで require すると便利。

test_helper.rb
def describe_internally(*args, &block)
  example = describe(*args, &block)
  cls = args[0]
  if cls.is_a? Class
    saved_private_instance_methods = cls.private_instance_methods
    example.before do
      cls.class_eval { public *saved_private_instance_methods }
    end
    example.after do
      cls.class_eval { private *saved_private_instance_methods }
    end
  end
end

これを require した RSpec ファイルで、describe の代わりに describe_internally を使えば、内部で private メソッドが public メソッドと同じように呼び出せる。

example_spec.rb
require 'test_helper'

describe_internally MyClass, "は、" do
  it "private メソッドをテストできる" do
    obj = MyClass.new
    # my_private_method は private メソッド
    obj.my_private_method.should == 1
  end
end
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15