获取rspec控制器测试以对BigDecimals进行浅层比较

时间:2013-06-05 18:23:22

标签: ruby-on-rails-3 rspec controller bigdecimal

我有一个带有测试的rspec控制器:

it "assigns all rate_card_details as @rate_card_details" do
  rate_card_detail = FactoryGirl.create(:rate_card_detail)
  get :index, {}, valid_session
  assigns(:rate_card_details).should eq([rate_card_detail])
end

对于大多数型号,这很好用。但是,在这种情况下,rate字段是小数。这导致rspec比较(由于某种原因)将BigDecimal的1个实例与另一个实例进行比较,包括它在内存中的位置。这是错误:

 Failure/Error: assigns(:rate_card_details).should eq([rate_card_detail])

   expected: [#<RateCardDetail rate_card_id: 1, item_id: 1, rate: #<BigDecimal:7f82dcdb0ae0,'0.6941E2',18(18)>, created_at: "2013-06-05 18:12:53", updated_at: "2013-06-05 18:12:53">]
        got: [#<RateCardDetail rate_card_id: 1, item_id: 1, rate: #<BigDecimal:7f82dc9a74d0,'0.6941E2',18(18)>, created_at: "2013-06-05 18:12:53", updated_at: "2013-06-05 18:12:53">]

2个BigDecimals具有相同的值,但它们是不同的对象。有没有办法让rspec在进行比较时将它们视为相等?

1 个答案:

答案 0 :(得分:0)

它不漂亮,但这适用于我

it "assigns all rate_card_details as @rate_card_details" do
  rate_card_detail = FactoryGirl.create(:rate_card_detail)
  get :index, {}, valid_session
  assigns(:rate_card_details).first.attributes.values.each_with_index do |rcd,i|
    r_c_d = rate_card_detail[i]
    if rcd.is_a?BigDecimal
      rcd = rcd.to_s
      r_c_d = r_c_d.to_s
    end
    expect(rcd).to eq(r_c_d)
  end
end