2017-03-09 44 views
-1

我正在學習Ruby on Rails。而在我的新項目中,我正在使用rspec,shoulda matchers。我只想知道如何改進編寫規格的方式。我還需要在其他模型規格中重複使用「術語」。我怎樣才能做到這一點?如何改進規格

感謝

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 
+4

您應該通過http://betterspecs.org/瞭解編寫測試用例的最佳實踐。 – Pramod

回答

0

這看起來像一個巨大的,端至端集成測試,所以無論你的代碼是所有撞上一個方法,或者你沒有正確的單元測試你的方法。

您在改善規格方面的第一步應與上述哪些問題相關聯;或者將你的代碼分解成可以直接測試的更小的方法,並且/或者測試你個人的公共方法。