我该如何改进规格

时间:2017-03-09 03:57:47

标签: ruby-on-rails ruby rspec factory-bot

我正在铁轨上学习红宝石。在我的新项目中,我正在使用rspec,shoulda matchers。我只是想知道如何改进编写规范的方式。我需要重复使用" Term"在其他型号规格中也是如此。我怎么能这样做?

由于

require 'rails_helper'

RSpec.describe Portfolio, type: :model do
  it { should validate_presence_of(:code) }
  it { should validate_presence_of(:name) }

  it "has a valid factory" do
      expect(FactoryGirl.create(:portfolio)).to be_valid
  end  

  it { should belong_to(:client) }
  it { should belong_to(:custodian) }

  let(:client) { FactoryGirl.create(:client) }
  let(:bank) { FactoryGirl.create(:bank)  }
  let(:product_cash) { ProductType.create(code: "CASH", name: "Cash") }
  let(:product_interest) { ProductType.create(code: "INTEREST", name: "Interest Bearing") }
  let(:product_discount) { ProductType.create(code: "DISCOUNT", name: "Discount") }
  let(:custodian) { FactoryGirl.create(:custodian)  }
  let(:portfolio) { Portfolio.create(client: client, custodian: custodian, code: "CASH", name: "Cash") }
  let(:user) { FactoryGirl.create(:user) }

  context 'under a portfolio' do
    it "will return total net asset value and liquidity" do
      Security.create(description: "first security")
      Security.create(description: "second security")

      portfolio = Portfolio.create(client: client, custodian: custodian, code: "BALANCED", name: "Balanced")
      Product.create(product_type: product_discount, name: "Bank Bills", liquid: true)
      RateSheetCategory.create(bank: bank, product: Product.first, name: :Large)

      rscb = RateSheetCategory.first
      rsct = RateSheetCategory.last

      Term.create(code: 30, name: "30 Days")
      Term.create(code: 60, name: "60 Days")
      Term.create(code: 90, name: "90 Days")
      Term.create(code: 120, name: "120 Days")
      Term.create(code: 180, name: "180 Days")
      Term.create(code: 360, name: "360 Days")

      rate1b = Rate.create(rate_sheet_category: rscb, date: "2017-03-01", rate: 0.0235, term: Term.find_by(code: 180))
      rate2b = Rate.create(rate_sheet_category: rscb, date: "2017-03-01", rate: 0.0245, term: Term.find_by(code: 60))   

      Deal.create(portfolio: portfolio, security: Security.first, amount: 2000000, transaction_type: 'P', deal_date: "2016-10-02", maturity_date: "2017-04-02", rate: rate1b, user: user)
      Deal.create(portfolio: portfolio, security: Security.find(2), amount: 1500000, transaction_type: 'P', deal_date: "2016-11-14", maturity_date: "2016-12-14", rate: rate2b, user: user)

      nav = portfolio.nav_at("2017-03-01")
      liquidity = portfolio.liquidity_at("2017-03-01")

      expect(nav.round(2)).to eq(43482525.12)
      expect(liquidity.round(2)).to eq(42481440.19)
  end
end  
end

2 个答案:

答案 0 :(得分:0)

这看起来像是一个巨大的端到端集成测试,所以要么你的代码都被抨击成一种方法,要么就是你没有正确地对你的方法进行单元测试。

改善规范的第一步应该与您遇到的上述问题相关联;或者将代码分解为可以直接测试的较小方法,和/或测试您的个人公共方法。

答案 1 :(得分:0)