【发布时间】:2017-01-30 13:15:36
【问题描述】:
我在编写规范时遇到了 validate_inclusion_of 匹配器的问题。
我目前的规范与用户和用户组有关。用户有一个用户组 ID。
我想检查一个用户的用户组 id 是否真的在当前用户组 id 列表中。
目前我的规格基本上是:
describe 'company_user_group list of valid IDs' do
let!(:company_user_group_everything) { FactoryGirl.create(:company_user_group_everything) }
let!(:company_user_group_nothing) { FactoryGirl.create(:company_user_group_nothing) }
it '' do
@company_user = FactoryGirl.create(:company_user, id: 1)
CompanyUser.current_id = @company_user.id
is_expected.to validate_inclusion_of(:company_user_group_id).in_array(CompanyUserGroup.full_list_of_ids)
end
end
但我得到的错误是:
1) CompanyUser validations company_user_group list of valid IDs should validate that :company_user_group_id is either ‹2› or ‹3›
Failure/Error: is_expected.to validate_inclusion_of(:company_user_group_id).in_array(CompanyUserGroup.full_list_of_ids)
NoMethodError:
undefined method `attribute_setter' for nil:NilClass
我尝试了各种不同的东西,并使用 byebug 等进行了调试,但没有什么对我有用。
例如
添加
@company_user_group_id = @company_user.company_user_group_id
并将 is_expected.to 行更改为
is_expected.to validate_inclusion_of(@company_user_group_id).in_array(CompanyUserGroup.full_list_of_ids)
我收到以下错误
1) CompanyUser validations company_user_group list of valid IDs should validate that :8 is either ‹8› or ‹9›
Failure/Error: is_expected.to validate_inclusion_of(@company_user_group_id).in_array(CompanyUserGroup.full_list_of_ids)
Shoulda::Matchers::ActiveModel::AllowValueMatcher::AttributeDoesNotExistError:
The matcher attempted to set :8 on the CompanyUser to 8, but that
attribute does not exist
看来,要检查的组 id 有效(例如 8)并且数组有效(例如 8 和 9)但匹配不起作用。
非常感谢任何帮助!
部分公司用户模型
# This model holds User identities for internal staff. This model is
# primarily intended for use in the xxxx application.
class CompanyUser LT ActiveRecord::Base
acts_as_authentic do |c|
c.merge_validates_uniqueness_of_email_field_options case_sensitive: false
c.merge_validates_length_of_password_field_options minimum: 8
if Rails.env.production?
c.logged_in_timeout = 30.minutes
else
c.logged_in_timeout = 90.minutes
end
end
# Constants
# relationships
belongs_to :company_user_group
# validations
validates :first_name, presence: true, length: { maximum: 20 }
validates :last_name, presence: true, length: { maximum: 20 }
validates :company_user_group_id, presence: true, numericality: { only_integer: true, greater_than: 0 }
validates :company_user_group_id, inclusion: { in: CompanyUserGroup.full_list_of_ids }, unless: 'Rails.env.test?'
validate :check_sys_admin_permission
如果“除非:'Rails.env.test?'”位被删除,大多数规范会由于某种未知原因而失败。只是提到它是相关的。
以及来自公司组模型的以下方法
# class methods
def self.full_list_of_ids
CompanyUserGroup.all.pluck(:id)
end
【问题讨论】:
-
您能否发布您实际测试的代码以及测试结果。
-
和某些公司模式一样?
-
是的,还有
CompanyUserGroup.full_list_of_ids -
好的,尽管我确实尝试在一个阶段只使用普通数组代替 full_list_of_ids 并且没有帮助,但会添加原始问题。谢谢。
-
我已添加到问题中。
标签: ruby-on-rails rspec authlogic shoulda