我试图设置来自不同银行的转帐金额的限制,我在模型上设置验证,评估帐户的收款人银行是否与其所在的银行不同。执行转移。但是,验证无法按预期工作,因为即使金额低于已设置的限制,它也不允许执行操作。
这是我进行的测试:
require 'rails_helper'
RSpec.describe Transfer, type: :model do
context "creates transfers" do
before do
@bank1 = Bank.create(name: "Bank A")
@bank2 = Bank.create(name: "Bank B")
@account1 = Account.create(holder: "Jim", bank: @bank1, funds: 25000)
@account2 = Account.create(holder: "Emma", bank: @bank2, funds: 2000)
@account3 = Account.create(holder: "Todd", bank: @bank1, funds: 5500)
end
it "between accounts, same entity" do
Transfer.create(account: @account1, bank: @account1.bank, recipient: @account3.id, ammount: 2000)
expect(Transfer.all.count).to eq(1)
expect(Transfer.last.ammount).to eq(2000)
expect(Transfer.last.account.funds).to eq(23000)
expect(Account.find(Transfer.last.recipient).funds).to eq(7500)
end
it "between accounts, different entities, over limit" do
Transfer.create(account: @account1, bank: @account1.bank, recipient: @account2.id, ammount: 1001)
expect(Transfer.all.count).to eq(0)
end
it "between accounts, different entities, charge a fee" do
Transfer.create(account: @account1, bank: @account1.bank, recipient: @account2.id, ammount: 999)
expect(Transfer.all.count).to eq(1)
end
end
end
以及相关模型:
class Transfer < ActiveRecord::Base
belongs_to :account
belongs_to :bank
before_save :bank_validator?
validates :ammount, numericality: { less_than_or_equal_to: 1000 }, unless: :bank_validator?
after_save :discount_from_origin
after_save :add_to_recipient
def discount_from_origin
last_transfer = Transfer.last
Account.discount_from_origin(last_transfer.account_id, last_transfer.ammount)
end
def add_to_recipient
last_transfer = Transfer.last
Account.add_to_recipient(last_transfer.recipient, last_transfer.ammount)
end
def bank_validator?
bank_id == Bank.find(Account.find(recipient).bank_id)[:id]
end
end
前两个测试通过,第三个测试失败,即使ammount小于1000的验证限制。
欢迎任何帮助。提前致谢
答案 0 :(得分:0)
最后,只需要删除before_save验证。