Rspec和FactoryGirl有几种型号
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Rspec和FactoryGirl有几种型号相关的知识,希望对你有一定的参考价值。
我是新的使用轨道上的测试,我有一些疑问...我需要测试几个模型,我知道如何测试基础知识,如验证和协会,但我不知道如何处理我需要的去做。
我有两个模型,PaymentDocument,PaymentAmount(PaymentDocument has_many PaymentAmount),每个模型都有一个名为“amount”的字段,PaymentDocument模型中的金额具有与之关联的每个PaymentAmount的总和。所以我需要对每个PaymentAmount金额应用一些数学运算并求它们,然后对PaymentDocument金额进行相同的数学运算并比较它以检查是否完全相等或我丢失了一些小数。
现在我有两个规格文件,一个用于PaymentDocument,另一个用于PaymentAmount,我如何同时测试两个模型(以验证每个模型的信息是否正确),然后应用我之前提到的数学运算?
payment_document_spec
require "rails_helper"
RSpec.describe PaymentDocument, type: :model do
describe "validations" do
it { is_expected.to validate_presence_of(:amount) }
it { is_expected.to validate_numerality_of(:amount).is_greater_than(0) }
end
describe "associations" do
it { is_expected.to belong_to(:payment_amounts) }
end
end
payment_amount_spec
require "rails_helper"
RSpec.describe PaymentAmount, type: :model do
describe "validations" do
it { is_expected.to validate_presence_of(:payment_document) }
it { is_expected.to validate_presence_of(:amount) }
it { is_expected.to validate_numerality_of(:amount).is_greater_than(0) }
end
describe "associations" do
it { is_expected.to have_many(:payment_document) }
end
end
编辑:
例
PaymentDocument
{
id => 1,
amount => 3540095,94
}
PaymentAmounts:
{
id => 1,
pd_id => 1,
amount => 40095.00,
}
{
id => 2,
pd_id => 1,
amount => 500000.94,
}
{
id => 2,
pd_id => 1,
amount => 3000000.00,
}
#The math operation is remove divide the amounts by 1000 and round them by 2
{
id => 1,
pd_id => 1,
amount => 40.10,
}
{
id => 2,
pd_id => 1,
amount => 500.00,
}
{
id => 2,
pd_id => 1,
amount => 3000.00,
}
#The sum of all the payment amounts is 3540.10 and if i do the same operation to the amount of the payment document the result is 3540.1 but in some cases it may not be equal so that's why i want to test this.
答案
我假设在创建payment_amount时,关联的payment_document金额会自动更新。如果是这种情况,您可以通过类似的方式进行测试。
describe '#payment' do
it 'should very amount' do
pd = Factory.create(:payment_document)
attributes = [ { pd_id: pd.id, amount: 40095.00 },
{ pd_id: pd.id, amount: 500000.94 },
{ pd_id: pd.id, amount: 3000000.00 }
]
attributes.each do |attrs|
Factory.create(:payment_amount, attrs)
end
total_amount = attributes.map{ |m| m[:amount]}.sum
expect(pd.reload.amount).to eq(total_amount)
end
end
注意:这是猜测,因为我不知道您的型号代码。
以上是关于Rspec和FactoryGirl有几种型号的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 rspec 测试 Cloudinary rails 和 Attachinary?