dgmora
dgmora

Reputation: 1269

Generating nested attributes for FactoryGirl objects with accepts_nested_attributes_for

I'm using RSpec and Factory Girl to test my application. What I'm trying to do is the following: I have a object which accepts nested attributes, and it is not valid that nested attribute. I want to test that the POST works:

let(:valid_attributes) { build(:user).attributes }
it "creates a new User" do      
  expect {
    post :create, {user: valid_attributes}, valid_session
  }.to change(User, :count).by(1)
end

That's the factory:

FactoryGirl.define do
  factory :user do |x|
    name "Homer"
    after(:build) do
      build :address
    end
  end
end

The problem is that the hash returned by build(:user).attributes does not have the address, although if I inspect the object created by build(:user), the address is correctly built.

Is there some way to easily generate a hash with the nested attributes?

Upvotes: 4

Views: 2232

Answers (2)

dgmora
dgmora

Reputation: 1269

Answering myself to show a technically working solution:

let(:valid_attributes) {attributes_for(:user, address_attributes: attributes_for(:address))}

This works, but I find it quite clunky. In complex cases the code would get incredibly verbose and ugly. As I would expect something nicer, I'm not voting this as a solution.

Upvotes: 5

Aleksey Shein
Aleksey Shein

Reputation: 7482

You can customize your object, while building it via parameters, so I'd solve your task this way:

let(:valid_attributes) { attributes_for(:user, address: attributes_for(:address)) }

Upvotes: 0

Related Questions