2

我无法弄清楚为什么我的第二个示例通过了,即使它应该失败了

这是我的 person_spec.rb:

require 'spec_helper'

describe Person do
  it "must have a first name" do
    subject { Person.new(first_name: "", last_name: "Kowalski") }
    subject.should_not be_valid
  end

  it "must have a last name" do
    subject { Person.new(first_name: "Jan") }
    subject.should_not be_valid
  end
end

这是我的人.rb

class Person < ActiveRecord::Base
  attr_accessible :first_name, :last_name

  validates :first_name, presence: true

  def full_name
    return "#{@first_name}  #{@last_name}"
  end
end

我的 rspec 输出:

Person
  must have a last name
  must have a first name

Finished in 0.09501 seconds
2 examples, 0 failures

Randomized with seed 51711

更糟糕的是,我的进一步示例以非常意想不到的方式失败/通过。似乎不知何故,我的主题是 Person 的一个实例,但既没有分配 first_name 也没有分配 last_name

4

1 回答 1

1

我认为你在这里有两个主要问题。首先,如果我没记错的话,您应该subject在组范围内使用,而不是在实际规范中使用。这是rspec 文档中的一个示例:

describe Array, "with some elements" do
  subject { [1,2,3] }
  it "should have the prescribed elements" do
    subject.should == [1,2,3]
  end
end

请注意,在块subject之外声明了。it所以,我认为在这里看到一些意想不到的行为是合理的。我还没有深入研究这里的源代码,但我觉得这很有教育意义。

其次,遵循David Chelimsky的这些指导方针可以大大简化您的规格。您的规范可能看起来更像这样:

describe Person do
  it { should validate_presence_of(:first_name) }
end

更短,更甜,并且可能会正常工作。

于 2012-10-16T14:22:39.850 回答