简体   繁体   English

试图了解为什么validates_presence_of测试失败

[英]Trying to understand why validates_presence_of test fails

I'm just starting to have a play with Rails (using Rspec and Shoulda Matchers) to build a demo blog. 我刚刚开始使用Rails(使用Rspec和Shoulda Matchers)来构建演示博客。

I've literally just started and my first test is failing but I can't understand why. 从字面上我才刚刚开始,我的第一个测试失败了,但是我不明白为什么。

I think I've set up everything correctly, but when I try to validate that a title is present on my Article model but it returns a failure 我认为我已经正确设置了所有内容,但是当我尝试验证我的Article模型上是否有标题但返回失败时

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

My model looks like this... 我的模特看起来像这样...

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

and my test... 和我的测试...

require 'rails_helper'

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

If I uncomment out the attr_accessor then the test passes but I understand that it's not required with Rails. 如果我取消对attr_accessor的注释,那么测试会通过,但我知道Rails不需要这样做。

What am I doing wrong? 我究竟做错了什么?

The attr_accessor is not required, as long as your articles database table has a title column. 只要您的articles数据库表具有title列,就不需要attr_accessor

You can check that in db/schema.rb . 您可以在db/schema.rb进行检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM