简体   繁体   English

对Rails模型中的总和进行单元测试

[英]unit testing a sum in rails model

I want to create a test which tests if my method is working correctly. 我想创建一个测试,测试我的方法是否正常工作。

The tonnage is calculated within my submission model and saved over there. 吨位是在我的提交模型内计算并保存在那里的。 I also need that function within my contest views and that's why I also included it in the contest model (is this correct?). 我在比赛视图中也需要该功能,这就是为什么我也将其包含在比赛模型中的原因(对吗?)。

class Contest < ActiveRecord::Base
  has_many :submissions 

  def tonnage
    self.submissions.sum(:tonnage)
  end

end

When I test (minitest) I get following error: 当我测试(最小)时,出现以下错误:

FAIL["test_0003_must have tonnage", #<Class:0x007fbcb9fac260>, 2015-09-29 21:23:47 +0200]
 test_0003_must have tonnage#Contest (1443554627.17s)
        --- expected
        +++ actual
        @@ -1 +1 @@
        -440
        +#<BigDecimal:7fbcbc9ac150,'0.0',9(27)>
        test/models/contest_test.rb:17:in `block (2 levels) in <top (required)>'

My test looks like this (minitest): 我的测试如下所示(最小):

describe Contest do
  let(:contest) { Contest.create(name: "test",
                                 admin_id: 1,) }

  it "must have tonnage" do
    contest.tonnage.must_equal 440
  end


end

What does the test output mean (the failure) and what is the proper way to unit test this? 测试输出是什么意思(失败),什么是对此进行单元测试的正确方法? I assume my method in my model is correct since it is working. 我认为我的模型中的方法正确,因为它可以工作。

Thanks to the comment below I found out that I was referring to the wrong contest. 感谢下面的评论,我发现我指的是错误的比赛。 Below is the proper test: 以下是正确的测试:

describe Contest do

  let (:default) { contests :default }

  it "must have tonnage" do
    default.tonnage.must_equal 440
  end

end

Your test shows 您的测试显示

    -440
    +#<BigDecimal:7fbcbc9ac150,'0.0',9(27)>

Meaning that you expected 440 (as your test asserts) but you got a BigDecimal object with value 0.0 . 这意味着您期望440 (如测试所断言),但是您得到了一个BigDecimal对象,其值为0.0 Likely because this is the database column type with a 0.0 default. 可能是因为这是默认值为0.0的数据库列类型。

My question: what is the sum message summing? 我的问题是: sum消息的总和是多少? Is it a column called tonnage ? 是一列叫做tonnage的列吗? Because I don't see that in your model. 因为我看不到您的模型。 Is it a column called tonnage inside submissions? 提交中是否有一个名为“ tonnage的列? The logic for your sum is not correct. 您的总和逻辑不正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM