0

我的 rspec 测试都运行良好,除非我复制对象以测试属性的唯一性。

这是模型:

应用程序/模型/驱动程序.rb

1.  class Driver < ActiveRecord::Base
2.    attr_accessible :last_name, :first_name, :short_name
# irrelevant code
18. before_save do
19.   last_name = last_name.gsub(' ', '-').capitalize!
20.   if last_name.include? '-'
21.     last_name[(last_name.index('-'))+1] = last_name[(last_name.index('-'))+1].capitalize!
22.   end
23. end
24. before_save do
25.   first_name = first_name.gsub(' ', '-').capitalize!
26.   if first_name.include? '-'
27.     first_name[(first_name.index('-'))+1] = first_name[(first_name.index('-'))+1].capitalize!
28.   end
29. end
30. before_save { short_name.downcase! }
# more irrelevant code
59. validates :short_name, presence: true, length: { maximum: 10 },
60.                   uniqueness: { case_sensitive: false }

因此,我通过复制驱动程序对象来测试 short_name 属性的唯一性,如下所示:

规格/模型/driver_spec.rb

require 'spec_helper'

  describe Driver do

    before do
      @driver = Driver.new(last_name: "Driver", first_name: "Example", short_name: "exdrvr")
    end

  subject { @driver }

  it { should respond_to(:last_name) }
  it { should respond_to(:first_name) }
  it { should respond_to(:short_name) }

  it { should be_valid }

  # a bunch of other tests, all of which work fine

  describe "when short name is already taken" do
    before do
      driver_with_same_short_name = @driver.dup
      driver_with_same_short_name.short_name = @driver.short_name.upcase
      driver_with_same_short_name.save
    end
    it { should_not be_valid }
  end

这是我运行所有测试时得到的结果:

.................................F....

Failures:

  1) Driver when short name is already taken 
     Failure/Error: driver_with_same_short_name.save
     NoMethodError:
       undefined method `gsub' for nil:NilClass
     # ./app/models/driver.rb:19:in `block in <class:Driver>'
     # ./spec/models/driver_spec.rb:128:in `block (3 levels) in <top (required)>'

Finished in 1.74 seconds
38 examples, 1 failure

Failed examples:

rspec ./spec/models/driver_spec.rb:130 # Driver when short name is already taken

因此,基本上所有测试都运行良好,除非我复制驱动程序对象。然后 last_name 属性突然为零。我尝试在模型文件的第 18-23 行注释掉 before_save 块,当然我也收到了相同的 first_name 错误消息。知道发生了什么吗?

4

1 回答 1

0

发现了问题:根本不在我的规范中,而是在模型的 before_save 块中。我将 driver.rb 中的第 18-23 行替换为

before_save { self.last_name = last_name.gsub(' ', '-').split('-').each { |x| x.capitalize! }.join('-') }

对于 first_name 块也是如此。测试现在运行良好。更重要的是,该模型现在实际上正在做我打算做的事情。我想这就是测试的目的!

于 2013-03-11T18:14:59.457 回答