【问题标题】:Rspec refactoring model issue (from rails test prescriptions 4)Rspec 重构模型问题(来自 Rails 测试处方 4)
【发布时间】:2014-11-17 05:11:41
【问题描述】:

我正在查看 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 时效果很好。当我重构任务模型以包含一些新功能时,我得到最后一个 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

非常感谢!

【问题讨论】:

    标签: ruby-on-rails ruby rspec


    【解决方案1】:

    对不起大家,问题最终是书籍注释中的拼写错误。问题是我试图指定任务是使用:

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

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

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

    我原以为模型中存在错误,但肯定是代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      相关资源
      最近更新 更多