How do I stub things in MiniTest?

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

提交回复
热议问题