Rspec应该是AttributeDoesNotExistError

问题描述 投票:0回答:1

我有一个附加到用户的客户端模型,所有规范测试都通过了。后来我意识到客户端不需要登录,所以我删除了关联。我添加了f_namel_name列。当我为validates_presence_of专栏运行shoulda matcher 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

schema.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 

client.rb

class Client < ApplicationRecord
  validates_presence_of :f_name, :l_name
  ...
end
ruby-on-rails-5 rspec-rails shoulda
1个回答
0
投票

你能尝试这样的事吗?

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
© www.soinside.com 2019 - 2024. All rights reserved.