【问题标题】:Rspec shoulda AttributeDoesNotExistErrorRspec 应该 AttributeDoesNotExistError
【发布时间】:2018-09-19 02:08:33
【问题描述】:

我有一个附加到用户的客户端模型,并且所有规范测试都通过了。后来我意识到客户不需要登录,所以我删除了关联。我添加了f_namel_name 列。当我为 f_name 列运行 shoulda matcher validates_presence_of 时,出现错误...

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

【问题讨论】:

  • 您是如何删除 association 的?您可以使用显示usersclients 定义的schema 更新您的问题吗?

标签: ruby-on-rails-5 rspec-rails shoulda


【解决方案1】:

你能试试这样的吗?

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

【讨论】:

  • 感谢您的回答。我不确定为什么它似乎保持短暂。我最终通过删除数据库然后删除客户端模型和文件(包括迁移)的所有痕迹来让它工作。然后我在没有测试、数据库表、模型或客户端控制器的情况下运行测试。然后我使用相同的 table_create 方法通过不同的迁移将表迁移回来。然后我将文件添加回来并进行了测试。我猜使用不同的迁移是解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多