This has nothing to do with FactoryGirl and everything to do with
ActiveRecord.
When you assign task.assignments.first to a local variable, and then
set status on that variable. you're mutating an instance of that
object. Every time you call task.assignments.first, you'll get a
different object; try running tasks.assignments.first.object_id ==
task.assignments.first.object_id. They're different! What does this
mean?
It means that if you mutate status on task.assignments.first (without
storing it to a local variable), you're mutating that instance without
saving it to the database. That's why, when you access it again, the
status is incorrect; you mutated a different instance, even though the
DATA itself (yes, including its primary key, id) is the exact same.
If you were to try this *without* FactoryGirl, you'd see the same
result - modifying the result of task.assignments.first (without
assigning it to a local variable first) won't actually change the
data, and when it's called again, you'll get a brand new instance from
the DB (without any of your previous mutation).
On Apr 24, 5:41 am, IAmNaN <
dger...@gmail.com> wrote:
> When I make an object with FactoryGirl, I can use a setter method on it,
> but not through an association.
>
> Assume Task has_many Assignments, and Assignment belongs_to a Task. Then
> the following works in the console but not in the spec.
>
> it 'does something useful' do
> task = FactoryGirl.create(:task)
> task.assignments.count.should eq 1
> task.assignments.first.status.should eq 0
> task.assignments.first.status = 1
> task.assignments.first.status.should eq 1 *# Fails with "expected: 1,
> got: 0"*
> *
> *
> * **# However....*
> a = task.assignments.first
> a.should eq task.assignments.first
> a.status = 1
> a.status.should eq 1 *# Passes!!!*