anu
anu

Reputation: 719

transient attribute in Factory Bot not working

I have this object that contains a word where the default value is 101.

 trait :word do
      transient do
        width 101
      end

      after(:create) do |object, evaluator|
        word_x = "x" * evaluator.width
        object.word = word_x
      end
    end

I call

create :object :word, width: 800

and it's perfect the object.word has a word of length 800 in the ruby test file.

However the class I'm testing shows that object.word has a word of length 101. It's like it forgets that I set it.

What's going on? .

EDIT: in my class, i query for objects using SQL. Would that be affecting the object?

Upvotes: 1

Views: 944

Answers (1)

Schwern
Schwern

Reputation: 165556

Your after(:create) function changes the object, but does not save the change. If you then query for that object from the database, it will not have the change.

obj = create(:object, :word, width: 800)
p obj.word # 800 long
p obj.changed? # true

# Re-fetch it from the database.
obj.reload
p obj.word # 101 long

It's more robust to do this as part of the word attribute.

factory :object do
  transient do
    word_width { 11 }
  end

  word { "x" * word_width }
end

Upvotes: 1

Related Questions