在接受测试中,我要测试gift.available_quantity的值是虚拟属性:
def available_quantity
pendings_orders = Order.where(status: 'pending')
order_lines_pending = OrderLine.where(order_id: pendings_orders)
gift_quantity_pending = order_lines_pending.sum do |oline|
return oline.quantity if oline.gift_ean13 == ean13
end
quantity - gift_quantity_pending
end
我没有测试我的代码,但这不是问题:)
问题是我的rspec在创建伪造订单之前评估了gift.available_quantity的价值:
require 'acceptance_helper'
resource 'Gifts' do
header 'Accept', 'application/json'
header 'Content-Type', 'application/json'
header 'Authorization', :authorization
get '/api/v1/gifts' do
let!(:member) { create(:member, id: 1) }
let(:user) { create(:user, :activated, member: member) }
let(:token) { Knock::AuthToken.new(payload: { sub: user.id }).token }
let(:authorization) { "Bearer #{token}" }
let!(:delivery_address) { create(:delivery_address, :favorited, member: member) }
let!(:gifts) { create_list(:gift, 2, :enabled, quantity: 4) }
let(:order_lines) { create(:order_line, gift_ean13: gifts.first.ean13, quantity: 1, order_id: order.id) }
let(:order_lines2) { create(:order_line, gift_ean13: gifts.last.ean13, quantity: 2, order_id: order.id) }
let!(:order) { create(:order, member: member, delivery_address: delivery_address) }
example_request 'Get gift list' do
expected_response = {
gifts: [
{
id: gifts.first.id,
name: gifts.first.name,
description: gifts.first.description,
reward_price: gifts.first.reward_price,
quantity: gifts.first.quantity,
date_from: gifts.first.date_from,
date_to: gifts.first.date_to,
image: nil,
quantity_alert: gifts.first.quantity_alert,
available_quantity: 3
},
{
id: gifts.last.id,
name: gifts.last.name,
description: gifts.last.description,
reward_price: gifts.last.reward_price,
quantity: gifts.last.quantity,
date_from: gifts.last.date_from,
date_to: gifts.last.date_to,
image: nil,
quantity_alert: gifts.last.quantity_alert,
available_quantity: 2
}
]
}
expect(status).to eq(200)
expect(response_body).to eq(expected_response.to_json)
end
end
end
我的订单以前没有创建过,所以gift.avalaible_quantity不好...
有人可以帮助我理解“ RSpec流程”吗?
答案 0 :(得分:2)
我认为问题在于规范运行之前没有创建您的order_lines。
使用let!
来创建它们,以便它们在available_quantity
方法运行时存在。
let!(:order_lines) { create(:order_line, gift_ean13: gifts.first.ean13, quantity: 1, order_id: order.id) }
let!(:order_lines2) { create(:order_line, gift_ean13: gifts.last.ean13, quantity: 2, order_id: order.id) }