Calculation delegating on Association


#1

Hi,

I’m experiencing a little bit of weird (to me at least) behaviour, and
would appreciate any thoughts…

I have two models, Story and Task. Story has_many Tasks

I’m building from the ground up test-first, so have been adding
“business logic” type methods to my models.

Story has a method called task_estimate, which is supposed to sum the
estimates on each task to give a total for the story.

Here’s the unit test in question:

def test_set_estimate
assert_equal tasks(:first_task).estimate
stories(:story_with_one_task).task_estimate
assert_equal 0, stories(:story_with_no_tasks).task_estimate
end

And here’s the method I write to pass the test
Here’s how I wrote it originally:

def task_estimate
tasks.sum(:estimate)
end

Now, the first assert passes, so I figure I’m using ‘sum’ properly. The
second assert fails saying expected 0, got nil.

I thought I’d found a bug, in summing a collection with no elements, and
right enough there’s no test for that in ActiveRecord, but when I do the
following in the console:

Story.create.task_estimate

I get 0 as expected. So as best I can tell I get nil when summing an
empty association during testing, but not in the console.

As I said above, I’d welcome any thoughts, suggestions, zen-slaps or
other beatings with the “obvious” stick.

A.


#2

Alan F. wrote:

def task_estimate
tasks.sum(:estimate)
end

Now, the first assert passes, so I figure I’m using ‘sum’ properly. The
second assert fails saying expected 0, got nil.

There’s definitely a bug in Active Record that causes empty sums
to be returned as nil rather than 0. The Calculations module casts
the nil result to to the column’s type, but this casting always returns
nil for a nil parameter.

I thought I’d found a bug, in summing a collection with no elements, and
right enough there’s no test for that in ActiveRecord, but when I do the
following in the console:

Story.create.task_estimate

I get 0 as expected. So as best I can tell I get nil when summing an
empty association during testing, but not in the console.

That’s strange, I always get nil.


We develop, watch us RoR, in numbers too big to ignore.