3

如何为私有方法写测试

 3 years ago
source link: https://mednoter.com/how-to-test-private-method.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何为私有方法写测试

今天第一次给 Rails 的私有方法写测试,查阅了些资料,目前比较流行的写法有两种。

class MyClass
  private

  def foo
    true
  end
  
  def bar
    true
   end
end

方法1:修改私有方法为 public

重新打开这个类,修改私有方法为 public。

class MyClass
  public :foo
end

class GoodsOrderTest < ActiveSupport::TestCase
 ...
 ...
end

方法2:使用 send

test "should foo" do
  instance = MyClass.new
  instance.send(:foo)
end

推荐第二种方法。

Stackoverflow: What’s the best way to unit test protected & private methods in Ruby?

吕小荣
23 December 2013

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK