ruby-on-rails-5 - Rspec 应该 AttributeDoesNotExistError
问题描述
我有一个附加到用户的客户端模型,所有规范测试都通过了。后来我意识到客户不需要登录,所以我删除了关联。我添加了f_name
和l_name
列。validates_presence_of
当我为该列运行应该匹配器时f_name
,我收到错误...
Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError:
The matcher attempted to set :f_name on the Client to nil, but that attribute does not exist.
我在应用程序中使用该属性,它确实存在。我可以使用种子文件填充数据库,并在应用程序中使用它。
我已经删除了数据库并重新创建了它,并db:test:prepare
认为测试数据库的架构可能没有改变。
为什么我会遇到这个问题?
rails_helper.rb
require 'spec_helper'
require File.expand_path('../../config/environment', __FILE__)
require 'rspec/rails'
require 'shoulda/matchers'
Shoulda::Matchers.configure do |config|
config.integrate do |with|
with.test_framework :rspec
with.library :rails
end
end
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :controller
config.include(Shoulda::Matchers::ActiveModel, type: :model)
config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end
架构.rb
create_table "clients", force: :cascade do |t|
t.string "f_name"
t.string "m_name"
t.string "l_name"
...
end
client_spec.rb
require "rails_helper"
RSpec.describe Client, type: :model do
it {should validate_presence_of(:f_name)}
it {should validate_presence_of(:l_name)}
...
end
客户端.rb
class Client < ApplicationRecord
validates_presence_of :f_name, :l_name
...
end
解决方案
你能试试这样的吗。
RSpec.describe Client, type: :model do
subject { Client.new(f_name: 'first_name', l_name: 'last_name') }
it { should validate_presence_of(:f_name) }
end
推荐阅读
- mysql - MySQL:左连接 RIGHT JOIN GROUP BY 错误
- sql - 如何比较 SQL 中的 smalldatetime?
- c++ - 为什么我的字符串值存储结构中的所有字符数组?
- google-chrome - Locking down chrome extension permissions
- javascript - Cannot interact with button using javascript
- angular - 我可以停止特定端点的默认角度重定向行为吗?
- python - 如何在有条件的情况下删除txt中的几行
- angular - 修改Angular html文件中变量的值
- java - 从 cmd 运行时遇到 java.lang.NoClassDefFoundError(错误名称:)问题
- python - 给定X和Y的坐标,如何在python中绘制相邻的多边形?