I want to test my service where I must to replace one module method by integer 50
for whole test. To do so I'm using Stub:
# tested service
module CashTransactions
class DistributeFunds
def initialize(users:, amount:)
@users = users
@amount = amount
end
def call
users.each do |user|
funds = CashTransactionSettings.calculate_amount_distribution(user, amount)
CashTransaction.create!(user: user, funds: funds)
end
end
end
end
Based on this source I've prepared following test:
test 'create CashTransaction records' do
user1_funds = CashTransactionSettings
user2_funds = CashTransactionSettings
refute user1_funds.calculate_amount_distribution
refute user2_funds.calculate_amount_distribution
CashTransactionSettings.stub :calculate_amount_distribution, 50 do
assert user1_funds.calculate_amount_distribution(user1, 100), 50
assert user2_funds.calculate_amount_distribution(user2, 100), 50
assert_equal 1, CashTransaction.where(user: user1, amount: 50).size
assert_equal 1, CashTransaction.where(user: user2, amount: 50).size
end
end
But instead of replacing CashTransactionSettings.calculate_amount_distribution
by 50
it calls it, where am I wrong? or maybe it's not possible in MiniTest?
You can use any_instance method and for that test block you will get the expected value as output of that method.
CashTransactionSettings.any_instance.stubs(:calculate_amount_distribution).returns(50)
And test case will be updated as below
test 'create CashTransaction records' do
user1_funds = CashTransactionSettings
user2_funds = CashTransactionSettings
refute user1_funds.calculate_amount_distribution
refute user2_funds.calculate_amount_distribution
CashTransactionSettings.any_instance.stubs(:calculate_amount_distribution).returns(50)
assert user1_funds.calculate_amount_distribution(user1, 100), 50
assert user2_funds.calculate_amount_distribution(user2, 100), 50
assert_equal 1, CashTransaction.where(user: user1, amount: 50).size
assert_equal 1, CashTransaction.where(user: user2, amount: 50).size
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.