Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I stub in setup method with Minitest?

How can I use stub method in setup? I only found the stub with block like this:

class FooTest < ActiveSupport::TestCase
  test 'for_something' do
    Foo.stub :some_method, 3 do
      #assert_equal
    end
  end  
end

But I want to stub for all tests. How can I stub it?

like image 201
ironsand Avatar asked Oct 08 '16 12:10

ironsand


People also ask

How do you stub a method in Minitest?

Stubbing in Minitest is done by calling . stub on the object/class that you want to stub a method on, with three arguments: the method name, the return value of the stub and a block. The block is basically the scope of the stub, or in other words, the stub will work only in the provided block.

What is Minitest in Ruby on Rails?

What is Minitest? Minitest is a testing suite for Ruby. It provides a complete suite of testing facilities supporting test-driven development (TDD), behavior-driven development (BDD), mocking, and benchmarking. It's small, fast, and it aims to make tests clean and readable.

What is stub in RSpec?

In RSpec, a stub is often called a Method Stub, it's a special type of method that “stands in” for an existing method, or for a method that doesn't even exist yet.

How do I run a Rails test?

2.7 The Rails Test Runner Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case. You can also run a particular test method from the test case by providing the -n or --name flag and the test's method name.


2 Answers

You can achieve that by overriding #run method in your test case:

class FooTest < ActiveSupport::TestCase
  def run
    Foo.stub :some_method, 3 do
      super
    end
  end

  test 'for_something' do
    #assert_equal
  end  
end

It's a common way to introduce the code that needs to be executed "around" every test case.

like image 197
lest Avatar answered Oct 01 '22 15:10

lest


I think this already answered here - https://stackoverflow.com/a/39081919/3102718

With gem mocha you can stub methods in setup or in test, e.g.:

require 'active_support'
require 'minitest/autorun'
require 'mocha/mini_test'

module Foo
end

class FooTest < ActiveSupport::TestCase
  setup do
    Foo.stubs(:some_method).returns(300)
  end

  test 'for_something' do
    assert Foo.some_method == 300
  end
end
like image 40
Alex Avoiants Avatar answered Oct 01 '22 15:10

Alex Avoiants