【问题标题】:Rails: How to setup a Unit test for my model with nested attributes?Rails:如何为具有嵌套属性的模型设置单元测试?
【发布时间】:2016-03-25 10:48:28
【问题描述】:

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

UserCompanyDeedSubtransaction,

Deedaccepts_nested_attributes_for(和validates_associated:subtransactions。我希望使用Minitestfixtures 测试我的模型验证。

我通过明确定义提交给我的模型的参数的哈希来设置我的测试。

我的模型测试:

   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  

<my tests here>

end

这是setup我的测试的正确方法吗?还是有更优雅或类似 Rails 的方法?

【问题讨论】:

    标签: ruby-on-rails unit-testing associations nested-attributes fixtures


    【解决方案1】:

    您可以使用setup 来定义您的设置方法。它将在测试之前运行。

    setup do
      @data_form = {
        title: Faker::Commerce.department,
        description: Faker::Lorem.paragraph,
        price: Faker::Commerce.price,
        category_id: 1
      }
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2022-01-23
      • 1970-01-01
      • 2013-12-28
      • 1970-01-01
      相关资源
      最近更新 更多