Rails: How do I write tests for a ruby module?

前端 未结 6 896
春和景丽
春和景丽 2021-01-31 02:22

I would like to know how to write unit tests for a module that is mixed into a couple of classes but don\'t quite know how to go about it:

  1. Do I test the instanc

6条回答
  •  悲&欢浪女
    2021-01-31 02:38

    IMHO, you should be doing functional test coverage that will cover all uses of the module, and then test it in isolation in a unit test:

    setup do
      @object = Object.new
      @object.extend(Greeter)
    end
    
    should "greet person" do
      @object.stubs(:format).returns("Hello {{NAME}}")
      assert_equal "Hello World", @object.greet("World")
    end
    
    should "greet person in pirate" do
      @object.stubs(:format).returns("Avast {{NAME}} lad!")
      assert_equal "Avast Jim lad!", @object.greet("Jim")
    end
    

    If your unit tests are good, you should be able to just smoke test the functionality in the modules it is mixed into.

    Or…

    Write a test helper, that asserts the correct behaviour, then use that against each class it's mixed in. Usage would be as follows:

    setup do
      @object = FooClass.new
    end
    
    should_act_as_greeter
    

    If your unit tests are good, this can be a simple smoke test of the expected behavior, checking the right delegates are called etc.

提交回复
热议问题