[英]Rails MiniTest stub module method for the whole test
I want to test my service where I must to replace one module method by integer 50
for whole test.我想测试我的服务,我必须用 integer
50
替换一个模块方法来进行整个测试。 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?但是它并没有用
50
替换CashTransactionSettings.calculate_amount_distribution
而是调用它,我哪里错了? or maybe it's not possible in MiniTest?或者在 MiniTest 中不可能?
You can use any_instance method and for that test block you will get the expected value as output of that method.您可以使用any_instance方法,对于该测试块,您将获得该方法的预期值 output。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.