簡體   English   中英

如何使用rspec為串行器編寫單元測試

[英]How to write unit test for serializer using rspec

嗨,我正在使用ruby-2.5.0和rails 5進行RoR項目。我有兩個模型Receipt和Receipt Items。 收據has_many receive_items。 收據序列化器:-

# frozen_string_literal: true

class ReceiptSerializer
  include JSONAPI::Serializer

  TYPE = 'reciept'
  attribute :name
  attribute :receipt_date
  attribute :address
  attribute :total_paid
  attribute :user_id

  attribute :receipt_date do
    object.receipt_date.strftime('%d/%m/%Y %H:%M:%S')
  end

  attribute :receipt_items do 
    object.receipt_items.map do |receipt_item|
      ::ReceiptItemSerializer.new(receipt_item).attributes
    end
  end
end

收貨項目序列化器:-

# frozen_string_literal: true

class ReceiptItemSerializer
  include JSONAPI::Serializer

  TYPE = 'reciept_item'
  attribute :item_name
  attribute :quantity
  attribute :price

end

我已經為兩個序列化器編寫了單元測試,如下所示:-receive_serializer_spec.rb

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ReceiptSerializer do
  let(:id) { 1 }
  let(:user_id) { 1 }
  let(:name) { 'IGA' }
  let(:address) { 'address' }
  let(:total_paid) { '100' }
  let(:receipt_date) { '12/04/2018 15:36:00' }
  let(:receipt) do
    Receipt.new(
      user_id: user_id,
      name: name,
      address: address,
      total_paid: total_paid,
      receipt_date: receipt_date
    )
  end

  subject { JSONAPI::Serializer.serialize(receipt) }

  it { is_expected.to have_jsonapi_attributes('user-id' => user_id) }

  it { is_expected.to have_jsonapi_attributes('address' => address) }

  it { is_expected.to have_jsonapi_attributes('total-paid' => total_paid) }

  it { is_expected.to have_jsonapi_attributes('receipt-date' => receipt_date) }

  it { is_expected.to have_jsonapi_attributes('receipt-date' => receipt_date) }
end

receive_item_serializer_spec.rb

# frozen_string_literal: true

require 'rails_helper'

RSpec.describe ReceiptSerializer do
  let(:receipt_id) { 1 }
  let(:item_name) { 'ABC' }
  let(:quantity) { 1 }
  let(:price) { '100' }
  let(:receipt_item) do
    ReceiptItem.new(
      receipt_id: receipt_id,
      item_name: item_name,
      quantity: quantity,
      price: price
    )
  end

  subject { JSONAPI::Serializer.serialize(receipt_item) }

  it { is_expected.to have_jsonapi_attributes('item-name' => item_name) }

  it { is_expected.to have_jsonapi_attributes('quantity' => quantity) }

  it { is_expected.to have_jsonapi_attributes('price' => price) }
end

現在,我不知道如何為我在receive_serializer.rb中定義的receive_items屬性編寫單元測試。 請幫我。 提前致謝。

你可以寫

it "serializes the receipt" do
  expect(subject).to include('item-name' => 'ABC', 'item-price' => '100') # ... etc
end

如果您已經單獨測試所有屬性的存在,則不確定測試是否具有巨大的價值。

我希望這個寶石對您有用https://github.com/collectiveidea/json_spec

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM