How do I stub things in MiniTest?

前端 未结 8 794
面向向阳花
面向向阳花 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:25

    You can always create a module in your test code, and use include or extend to monkey-patch classes or objects with it. eg (in book_test.rb)

    module BookStub
      def title
         "War and Peace"
      end
    end
    

    Now you can use it in your tests

    describe 'Book' do
      #change title for all books
      before do
        Book.include BookStub
      end
    end
    
     #or use it in an individual instance
     it 'must be War and Peace' do
       b=Book.new
       b.extend BookStub
       b.title.must_equal 'War and Peace'
     end
    

    This allows you to put together more complex behaviours than a simple stub might allow

    0 讨论(0)
  • 2020-12-02 10:30

    You cannot stub all instances of a class, but you can stub any instance method of a given object like this:

    require "minitest/mock"
    
    book = Book.new
    book.stub(:title, 'War and Peace') do
      assert_equal 'War and Peace', book.title
    end
    
    0 讨论(0)
提交回复
热议问题