【问题标题】:RSpec Model Testing: FailuresRSpec 模型测试:失败
【发布时间】:2014-11-05 09:23:57
【问题描述】:

我正在自学 RSpec (v3.1.7)。我已将带有rails g rspec:install 的 rspec 安装到现有的 Rails 应用程序中 - 新创建的。

我创建了一个模型:rails g rspec:model zombie。运行迁移,一切顺利。

在:app/models/zombie.rb:

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

在:app/spec/models/zombie_spec.rb:

require 'rails_helper'

RSpec.describe Zombie, :type => :model do
  it 'is invalid without a name' do
    zombie = Zombie.new
    zombie.should_not be_valid
  end  
end

我在终端运行时(在应用程序目录中):rspec spec/models 我得到:

F

Failures:

1) Zombie is invalid without a name
 Failure/Error: zombie.should_not be_valid
 NoMethodError:
   undefined method `name' for #<Zombie id: nil, created_at: nil, updated_at: nil>
 # ./spec/models/zombie_spec.rb:6:in `block (2 levels) in <top (required)>'

我正在关注视频教程,然后我按照视频(使用 RSpec 测试)一直到后者。我喜欢在第2章减肥。我错过了什么吗?该视频是否使用旧版本的 rspec 作为视频教程?

在我的迁移文件中:

class CreateZombies < ActiveRecord::Migration
  def change
     create_table :zombies do |t|

      t.timestamps
     end
  end
end

【问题讨论】:

标签: ruby-on-rails-4 rspec rspec-rails rspec3


【解决方案1】:

您的模型不知道 name 是什么,因为您没有在迁移中定义属性:

class CreateZombies < ActiveRecord::Migration
  def change
     create_table :zombies do |t|
      t.string :name
      t.timestamps
     end
  end
end

然后运行:

rake db:migrate

那么这应该可以正常工作:

z = Zombie.new(name: 'foo')
z.name
 => 'foo'

【讨论】:

  • 没有任何作用。在问问题之前我确实尝试过添加表名,但同样的事情。
  • 要努力,因为这是问题
【解决方案2】:

我认为您缺少 name 属性。以下迁移文件将为僵尸模型添加名称属性:

class AddNameToZombies < ActiveRecord::Migration
  def change
    add_column :zombies, :name, :string
  end
end

最后运行以下命令:

rake db:migrate

rake db:test:prepare

就是这样

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多