Ruby on rails 使用CanCan测试哈希键的值
我有一个UserProfile模型,它带有一个序列化哈希,定义了各种隐私选项:Ruby on rails 使用CanCan测试哈希键的值,ruby-on-rails,ruby,hash,cancan,Ruby On Rails,Ruby,Hash,Cancan,我有一个UserProfile模型,它带有一个序列化哈希,定义了各种隐私选项: class UserProfile < ActiveRecord::Base attr_accessible :bio, :first_name, :last_name, :location, :website_url, :vanity_url, :avatar belongs_to :user has_one :avatar before_create :default_privacy
class UserProfile < ActiveRecord::Base
attr_accessible :bio, :first_name, :last_name, :location, :website_url, :vanity_url, :avatar
belongs_to :user
has_one :avatar
before_create :default_privacy
PRIVACY_SETTINGS = [:public, :app_global, :contacts, :private]
serialize :privacy_options, Hash
private
def default_privacy
return if self.privacy_options
self.privacy_options = {:personal => :app_global, :contacts => :app_global, :productions => :app_global}
end
end
但是,以下单元测试产生test\u user\u can\u read\u profile\u personal\u scope\u set\u to\u public(能力测试):
TypeError:无法将符号转换为整数
:
require 'test_helper'
class AbilityTest < ActiveSupport::TestCase
def setup
@up = user_profiles(:joes_user_profile)
@ability = Ability.new(@user)
end
test "user can only read profile with personal scope set to public" do
assert @ability.can?(:read, @up)
@up.personal_privacy = :private
@up.save
refute @ability.can?(:read, @up)
end
end
需要“测试助手”
类AbilityTest
我对Ruby和Rails非常陌生。测试能力模型中隐私选项键值的正确方法是什么?替换此选项:
can :read, UserProfile, :privacy_options[:personal].eql?(:public)
为此:
can :read, UserProfile do |profile|
profile.privacy_options[:personal] == :public
end
问题在于:
是无效的符号语法:privacy\u options[:personal]
- CanCan需要选项哈希或块作为
方法的(optionnal)参数(有关更多信息,请参阅)can
作为旁注,如果可能的话,您不应该将隐私选项序列化为散列-正如Cancan的文档所述,块条件仅在加载实际记录时使用。如果您希望能够对集合设置授权,则需要一个哈希条件(可以转换为),这反过来又需要您的条件以属性(或至少可以通过SQL查询表示的内容)为目标。太好了!这正如预期的那样有效。我将对其进行重构,这样我们就不必首先加载我们正在授权的记录。
can :read, UserProfile do |profile|
profile.privacy_options[:personal] == :public
end