【问题标题】:Trying to understand why validates_presence_of test fails试图理解为什么 validates_presence_of 测试失败
【发布时间】:2017-06-04 11:58:46
【问题描述】:

我刚刚开始使用 Rails(使用 Rspec 和 Shoulda Matchers)来构建一个演示博客。

我刚刚开始,我的第一个测试失败了,但我不明白为什么。

我认为我已经正确设置了所有内容,但是当我尝试验证我的文章模型上是否存在标题但它返回失败时

Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError:
   The matcher attempted to set :title on the Article to nil, but that
   attribute does not exist.

我的模型看起来像这样......

class Article < ApplicationRecord
  # attr_accessor :title
  validates_presence_of :title
end

还有我的测试...

require 'rails_helper'

RSpec.describe Article do
  it { should validate_presence_of :title }
end

如果我取消注释 attr_accessor 则测试通过,但我知道 Rails 不需要它。

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails rspec shoulda


    【解决方案1】:

    attr_accessor 不是必需的,只要您的articles 数据库表有一个title 列。

    您可以在db/schema.rb 中查看。

    【讨论】:

    • 非常感谢@hugh-middleton,我已经更新了迁移文件,但没有意识到架构。不确定它从哪里读取属性。
    • 不用担心。是的,只要您实际运行迁移,schema.rb 就会自动更新。
    猜你喜欢
    • 2018-04-04
    • 2012-04-21
    • 1970-01-01
    • 2019-04-27
    • 2021-01-28
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多