Rails 3.2 - RSpec - 运行RSpec测试时出现未定义的方法错误

时间:2012-02-17 18:05:44

标签: ruby-on-rails ruby-on-rails-3 rspec null

我正在为Rails 3.2应用程序编写一些RSpec测试,并且Rspec在此测试中不断崩溃:

describe Person do
  before { @person = Person.new(names: [Factory.create(:name)], DOB: Date.today) }
  subject { @person }

  [:names,:DOB,:phone,:email,:address1,:address2,
  :city,:state,:zip,:notes,:last_seen].each do |value|
    it { should respond_to(value) }
  end

  it { should be_valid }

  describe "when no name is present" do
    @person.names = []
    it {should be_invalid}
  end

  describe "when no DOB is present" do
    @person.DOB = nil
    it {should be_invalid}
  end
end

当我运行RSpec时,我获得此行的undefined method 'names=' for nil:NilClass (NoMethodError)@person.names = []

如果我删除了无名测试,那么它会在@person.DOB = nil

上崩溃

看起来不知怎的,@person块之前没有设置describe。是否有一些RSpec的怪癖我不见了?

修改:人物模型:

class Person < ActiveRecord::Base
  has_and_belongs_to_many :names
  validates_presence_of :DOB
end

非常简单。有一个names_people连接表来连接Name和Person。就像我说的,我通常可以通过names=()访问名称。这是关于这一次测试的事情。

1 个答案:

答案 0 :(得分:0)

解决了它。我不得不再次使用before方法对@person进行更改。例如,我不得不使用它:

describe "when no name is present" do
  before { @person.names = [] }
  it {should be_invalid}
end

而不是:

describe "when no name is present" do
  @person.names = []
  it {should be_invalid}
end