尝试在Rails模型中包含关注点时出现“ NameError:未初始化的常量”

时间:2019-01-25 21:54:40

标签: ruby-on-rails ruby rails-activerecord activesupport-concern ruby-on-rails-6

我正在尝试在Rails ApplicationRecord对象中包含一个关注点。

这是模型文件:/app/models/item.rb

class Item < ApplicationRecord
  include Items::Validating
end

以下是关注文件:/app/models/concerns/items/validating.rb

module Items
  module Validating

    extend ActiveSupport::Concern
    included do
      before_create :set_defaults
      validates :status, presence: true
      validates :user_id, presence: true
      validates :day, presence: true
    end

    def set_defaults
      self.status ||= 'active'
      self.day ||= Date.today
    end

  end
end

当我尝试运行测试时,出现以下错误:

$ rails t

Error:
SessionsControllerTest#test_should_destroy_session:
NameError: uninitialized constant Item::Items
    app/models/item.rb:3:in `<class:Item>'
    app/models/item.rb:1:in `<main>'

这很奇怪,因为我包括了对User模型的关注,并且它完全可以正常工作。我不知道这里有什么不同。


更新:运行服务器或控制台时没有错误,仅在运行测试时。这是SessionsControllerTest文件:

require 'test_helper'

class SessionsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @session = sessions(:one)
  end

  test "should fail to create session because of no email" do
    assert_difference('Session.count', 0) do
      post sessions_url, params: { email: 'no-email-found@no-email.com', password: 'password_hashed' }
    end

    assert_redirected_to login_url
  end

  test "should fail to create session because of no password" do
    assert_difference('Session.count', 0) do
      post sessions_url, params: { email: 'jerry@vandalay.com', password: 'password_hashed_wrong' }
    end

    assert_redirected_to login_url
  end

  test "should create session" do
    email = 'jerry@vandalay.com'
    assert_difference('Session.count') do
      post sessions_url, params: { email: email, password: 'password_hashed' }
    end

    user = User.first_with_email(email)
    assert_redirected_to dashboard_url
  end

  test "should destroy session" do
    get logout_url

    assert_redirected_to login_url
  end

end

0 个答案:

没有答案