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?
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? 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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With