Rspec和FactoryGirl有几种型号

时间:2018-05-16 15:52:47

标签: ruby-on-rails ruby rspec

我是新的在轨道上使用测试我有一些疑问...我需要测试几个模型,我知道如何测试基础知识,如验证和关联,但我不知道如何接近我需要做什么。

我有两个模型,PaymentDocument,PaymentAmount(PaymentDocument has_many PaymentAmount),每个模型都有一个名为“amount”的字段,PaymentDocument模型中的金额具有与之关联的每个PaymentAmount的总和。所以我需要对每个PaymentAmount金额应用一些数学运算并求它们,然后对PaymentDocument金额进行相同的数学运算并比较它以检查是否完全相等或者我丢失了一些小数。

现在我有两个specs文件,一个用于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. 

1 个答案:

答案 0 :(得分:0)

我假设在创建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

注意:这是猜测,因为我不知道您的型号代码。