2

失敗するはずなのに、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

ここには2つの主な問題があると思います。まず、私が間違っていなければsubject、実際の仕様ではなく、グループスコープで使用することになっています。rspec docsの例を次に示します。

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 に答える