Skip to content

Instantly share code, notes, and snippets.

@daqing
Created June 27, 2019 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daqing/1a67f7343de4eb71e510432392d5f8be to your computer and use it in GitHub Desktop.
Save daqing/1a67f7343de4eb71e510432392d5f8be to your computer and use it in GitHub Desktop.
How to test methods that call other methods

对于如何测试下面的方法,我现在的思考是:

def do_something
  do_action_one
  do_action_two(10)
  another.do_abc
  
  if ok?
    do_action_z
  end
end

对于测试 do_something 的行为,只需要验证:

  1. 它会调用 do_action_one 方法,至于 do_action_one 会做什么,不需要关心,因为会有针对 do_action_one 的单独测试。

    describe "#do_something" do
      it "calls do_actions_one" do
        obj.expects(:do_action_one).once
        
        obj.do_something
      end
    end
    
    describe "#do_action_one" do
      it "does ...." do
        # tests do_action_one
      end
    end
    
  2. 它会调用 do_action_two,并且参数是10。同理,do_action_two要做什么不需要关心。

  3. 它会调用 another 对象的 do_abc 方法。同理,do_abc 方法会有单独的测试来保证其行为。

  4. 当 ok? 返回 true 时,会调用 do_action_z 方法。这里会用到 context 和 stubs,类似以下代码:

    context "when ok? is true" do
      before do
        obj.stubs(:ok?).returns(true)
      end
      
      it "calls do_action_z" do
        obj.expects(:do_action_z).once
        
        obj.do_something
      end
    end
    
@marshluca
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment