Rails:如何对嵌套属性的验证进行单元测试?

时间:2016-03-25 11:09:01

标签: ruby-on-rails validation unit-testing nested-attributes

我的应用中有以下has_many模型关联:

User< Company< Deed< Subtransaction

其中Deed accepted_nested_attributes_for :subtransactions。我希望使用Minitestfixtures测试我的模型验证。

但是,我在测试嵌套属性的有效性方面遇到了麻烦。例如,如果我使用

清除所有嵌套属性

@deed.subtransactions.clear我正确地得到了模型无效的测试响应。

然而

@deed.subtransactions.first.num_shares = " "似乎不起作用。

如何正确测试这些嵌套属性的有效性?

我的测试:

  class DeedTest < ActiveSupport::TestCase

        def setup
            @user = users(:dagobert)
            @newco = companies(:newco)
            params = { :deed => 
                  {
                   :date => deeds(:inc_new).date,
                   :subtransactions_attributes =>
                        { '1' => 
                             {
                              :shareholder_name => "Shareholder 1",
                              :num_shares => subtransactions(:new_subt1).num_shares
                              },
                          '2' => 
                              {
                              :shareholder_name => "Shareholder 2",
                              :num_shares => subtransactions(:new_subt2).num_shares
                              } 
                        }
                  }
              }
           @deed = @newco.deeds.new(params[:deed]) 

        end

        # test: does not raise any error messages
           test "num_shares should be present for a subtransaction" do
              @deed.subtransactions.first.num_shares = nil
              assert_not @deed.valid?
           end            

        # test passing: The params are submitted correctly and pass validation 
        test "fixture values should be valid" do
            assert @deed.valid?
        end

        # test passing: I can test the validity of deed attributes
        test "date should be present" do
            @deed.date = " "
            assert_not @deed.valid?
        end    

        # test passing: when I clear @deed.subtransactions the object is no longer valid 
        test "a subtransaction should be present" do
             @deed.subtransactions.clear
            assert_not @deed.valid?
        end

end

更新

Deed型号:

class Deed < ActiveRecord::Base
  belongs_to :company
  has_many :subtransactions, dependent: :destroy

  accepts_nested_attributes_for :subtransactions, allow_destroy: true,
                                                  reject_if: ->(a) { a['shareholder_name'].blank? && a['num_shares'].blank? }

  validates_associated :subtransactions

  validates :date, presence: true
  validates :subtransactions, presence: true

end

Subtransaction型号:

class Subtransaction < ActiveRecord::Base
  belongs_to :deed
  belongs_to :shareholder

  validates :num_shares,  presence: true, length: { maximum: 50 },
        :numericality => { only_integer: true } 

  validates :shareholder_name, presence: true

  # end class
end

0 个答案:

没有答案