【问题标题】:why does this not work in Rspec zombie.should_not be_valid为什么这在 Rspec 僵尸中不起作用.should_not be_valid
【发布时间】:2013-01-30 12:47:20
【问题描述】:

app/models/zombie.rb

class Zombie < ActiveRecord::Base
    attr_accessible :name
    validates :name, presence: true
end

spec/models/zombie_spec.rb

require 'spec_helper'

describe Zombie do

    it "is invalid without a name" do
        zombie = Zombie.new
        zombie.should_not be_valid
    end
end

错误

僵尸 没有名字就无效 (FAILED - 1) 失败:

 1) Zombie is invalid without a name
    Failure/Error: zombie.should_not be_valid
    ActiveRecord::StatementInvalid:
      Could not find table 'zombies'
    # ./spec/models/zombie_spec.rb:5:in `new'
    # ./spec/models/zombie_spec.rb:5:in `block (2 levels) in <top (required)>'

在 0.02912 秒内完成 7 个示例,1 个失败

失败的例子:

rspec ./spec/models/zombie_spec.rb:4 # 没有名字的僵尸无效

用种子 12906 随机化

【问题讨论】:

  • 你得到什么错误信息?
  • 另外,如果 :name 是僵尸数据库表中的列,则不需要初始化方法定义的 attr_accessor 行。等效功能将作为 ActiveRecord 的一部分提供。
  • 您是否运行迁移来创建僵尸表?

标签: ruby-on-rails rspec


【解决方案1】:

您不应该在 ActiveRecord 类中定义 initialize 方法。

当我定义了初始化方法时,出现了这个错误:

 Failure/Error: zombie = Zombie.new
 NoMethodError:
   undefined method `delete' for nil:NilClass

没有它,它会如你所愿地过去。

因此,将您的模型更改为以下,您的规格将通过。

class Zombie < ActiveRecord::Base
  attr_accessible :name
  validates :name, presence: true
end

或者...如果您觉得必须这样做,请务必先致电super

def initialize(options={})
  super
  self.name = options[:name]
end

【讨论】:

    【解决方案2】:

    您是否运行了 rake db:test:load 以便将数据库的架构加载到测试数据库上?

    您的测试也不正确,您正在测试您的模型无效但您没有测试您的模型无效,因为它的名称不存在,您应该执行类似的操作

    it "is invalid without a name" do
        zombie = Zombie.new
        zombie.should_not be_valid
        zombie.errors[:name].should_not be_blank
    end
    

    这样你就真的知道name属性有错误了

    【讨论】:

      【解决方案3】:

      谢谢大家,我没有运行迁移,所以运行 rake db:migrate 修复了它

      【讨论】:

        【解决方案4】:

        我也在学习本教程并且遇到了同样的问题。我进行了迁移,但仍然没有得到想要的结果。正如 arieljuod 提到的,运行 $ rake db:test:load 可以解决问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-08
          • 2013-04-11
          • 2011-03-14
          • 2013-05-01
          • 2021-08-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多