Rspec重构模型问题(来自rails测试处方4)

我正在通过rails 4处方,我有一个重构问题。 我正在创建一个项目管理应用程序,我正在构建以学习TDD。我遇到的问题是特定的测试中断,我无法弄清楚它为什么会这样。 这是现在可以使用的任务模型,但是当我将其切换到下面的新任务时会中断:

class Task attr_accessor :size, :completed_at def initialize(options = {}) @completed = options[:completed] @size = options[:size] end def mark_completed @completed = true end def complete? @completed end end 

这是项目模型:

 class Project attr_accessor :tasks def initialize @tasks = [] end def incomplete_tasks tasks.reject(&:complete?) end def done? incomplete_tasks.empty? end def total_size tasks.sum(&:size) end def remaining_size incomplete_tasks.sum(&:size) end end 

rspec测试如下所示:

 require 'rails_helper' RSpec.describe Project do describe "initialization" do let(:project) { Project.new } let(:task) { Task.new } it "considers a project with no test to be done" do expect(project).to be_done end it "knows that a project with an incomplete test is not done" do project.tasks << task expect(project).not_to be_done end it "marks a project done if its tasks are done" do project.tasks << task task.mark_completed expect(project).to be_done end end # describe "estimates" do let(:project) { Project.new } let(:done) { Task.new(size: 2, completed: true) } let(:small_not_done) { Task.new(size: 1) } let(:large_not_done) { Task.new(size: 4) } before(:example) do project.tasks = [done, small_not_done, large_not_done] end it "can calculate total size" do expect(project.total_size).to eq(7) end it "can calculate remaining size" do expect(project.remaining_size).to eq(5) end end # end 

当我在那里运行rspec时,效果很好。 当我重构任务模型以包含一些新function时, 我得到最后一个rspec失败 – 即它认为剩下7个测试而不是之前通过的5个测试这是新的任务模型。

 class Task attr_accessor :size, :completed_at def initialize(options = {}) mark_completed(options[:completed_at]) if options[:completed_at] @size = options[:size] end def mark_completed(date = nil) @completed_at = (date || Time.current) end def complete? completed_at.present? end def part_of_velocity? return false unless complete? completed_at > 3.weeks.ago end def points_toward_velocity if part_of_velocity? then size else 0 end end end 

非常感谢!

对不起大家,这个问题最终成了书中笔记的一个错字。 问题是我试图指定任务是使用以下方式完成的:

 let(:done) { Task.new(size: 2, completed: true) } 

在重构任务时,代码更改为completed_at,因此我需要指定如下内容:

 let(:old_done) { Task.new(size: 2, completed_at: 6.months.ago) } 

我原本以为模型中有一个错误,但绝对是代码。