Rails活动记录对象。 " St"表现出乎意料

时间:2015-04-15 17:51:32

标签: ruby-on-rails ruby-on-rails-4

我正在阅读Rails 4 Test Prescriptions。我对'Sum'方法有一个有趣的观察。书中有两个模型:项目和任务

class Project < ActiveRecord::Base

  has_many :tasks
  ...
end

class Task < ActiveRecord::Base
  belongs_to :project
  ...
end

#Rspec code
describe "estimates" do
  let(:project) { Project.new }
  let(:newly_done) { Task.new(size: 3, completed_at: 1.day.ago)}
  let(:old_done) { Task.new(size: 2, completed_at: 6.months.ago)}
  let(:small_not_done) { Task.new(size: 1)}
  let(:large_not_done) { Task.new(size: 4)}

  before(:each) do
    project.tasks = [newly_done, old_done, small_not_done, large_not_done]
    othertasks = [newly_done, old_done,small_not_done, large_not_done]

    puts "Size of project is #{project.tasks.sum(&:size)}" # line 1 <- 0
    puts "Size of othertasks is #{othertasks.sum(&:size)}" # line 2 <- 10
  end
end

如注释所示,第1行打印0,第2行打印10(预期结果)。我也尝试使用 let!代替let并获得相同的结果。 我想知道这种不一致行为的原因是什么。我正在使用ruby 2.2和Rails 4.2.1

修改   我试过了:  1.在添加任务后保存项目

   ...
   project.tasks <<  [newly_done, old_done, small_not_done, large_not_done]
   project.save
   ... 

和2.使用create而不是new

      ...
      let(:project) { Project.create }
      let(:newly_done) { Task.create(size: 3, completed_at: 1.day.ago)}
      let(:old_done) { Task.create(size: 2, completed_at: 6.months.ago)}
      let(:small_not_done) { Task.create(size: 1)}
      let(:large_not_done) { Task.create(size: 4)}
      ...

并且仍然得到相同的结果。

1 个答案:

答案 0 :(得分:0)

结果我需要在执行聚合操作之前添加to_a。   工作代码是:

 #Rspec code
  describe "estimates" do
    let(:project) { Project.new }
    let(:newly_done) { Task.new(size: 3, completed_at: 1.day.ago)}
    let(:old_done) { Task.new(size: 2, completed_at: 6.months.ago)}
    let(:small_not_done) { Task.new(size: 1)}
    let(:large_not_done) { Task.new(size: 4)}

    before(:each) do
      project.tasks = [newly_done, old_done, small_not_done, large_not_done]
      othertasks = [newly_done, old_done,small_not_done, large_not_done]

      puts "Size of project is #{project.tasks.to_a.sum(&:size)}" # line 1 <- 10
      puts "Size of othertasks is #{othertasks.sum(&:size)}" # line 2 <- 10
    end
  end

请注意第1行中的 to_a