How do I stub things in MiniTest?

前端 未结 8 919
面向向阳花
面向向阳花 2020-12-02 09:46

Within my test I want to stub a canned response for any instance of a class.

It might look like something like:

Book.stubs(:title).any_instance().ret         


        
8条回答
  •  忘掉有多难
    2020-12-02 10:22

    You can easily stub class methods in MiniTest. The information is available at github.

    So, following your example, and using the Minitest::Spec style, this is how you should stub methods:

    # - RSpec -
    Book.stubs(:title).any_instance.returns("War and Peace")
    
    # - MiniTest - #
    Book.stub :title, "War and Peace" do
      book = Book.new
      book.title.must_equal "War and Peace"
    end
    

    This a really stupid example but at least gives you a clue on how to do what you want to do. I tried this using MiniTest v2.5.1 which is the bundled version that comes with Ruby 1.9 and it seems like in this version the #stub method was not yet supported, but then I tried with MiniTest v3.0 and it worked like a charm.

    Good luck and congratulations on using MiniTest!

    Edit: There is also another approach for this, and even though it seems a little bit hackish, it is still a solution to your problem:

    klass = Class.new Book do
      define_method(:title) { "War and Peace" }
    end
    
    klass.new.title.must_equal "War and Peace"
    

提交回复
热议问题