Matthias
Matthias

Reputation: 1953

Rails: How to setup a Unit test for my model with nested attributes?

I have a the following has_many / belongs_to model associations in my app:

User < Company < Deed < Subtransaction,

where Deed accepts_nested_attributes_for (and validates_associated) :subtransactions. I wish to test my Model validations using Minitest and fixtures.

I've set up my test by explicity defining the hash of the params submitted to my model.

My Model test:

   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

Is this the proper way to setup my test? Or are there more elegant or Rails-like methods?

Upvotes: 0

Views: 620

Answers (1)

陳黑弟
陳黑弟

Reputation: 11

You can use setup to define your setup method. It will run before testing.

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

Upvotes: 1

Related Questions