【问题标题】:Rails 3.2 - RSpec - Undefined method error while running RSpec testRails 3.2 - RSpec - 运行 RSpec 测试时出现未定义的方法错误
【发布时间】:2012-02-18 14:18:10
【问题描述】:

我正在为 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 的一些怪癖吗?

编辑: Person 模型:

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

很简单。有一个names_people 连接表来连接名称和人员。就像我说的,我通常可以通过names=() 访问名称。这是关于这个测试的东西。

【问题讨论】:

  • Person.new 不应该是Person.new(:names =&gt; [Factory.create(:name)], :DOB =&gt; Date.today)吗?
  • 确保你已经运行了rake db:test:prepare——当活动记录在迁移后无法找到测试数据库上的列时,这有时会让我感到困惑。
  • 您好,您能给我们提供有关 Person 模型的更多信息吗?似乎没有 name 属性的访问器,因此方法 names=() 不存在。

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


【解决方案1】:

解决了。我不得不再次使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多