0

さまざまなプライバシー オプションを定義するシリアル化されたハッシュを持つ 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

  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

次のように、CanCan を使用してユーザー プロファイルへのアクセスを承認しています。

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    can :create, UserProfile
    can :read, UserProfile, :privacy_options[:personal].eql?(:public)
    if user.role? :user
      can :read, UserProfile, privacy_options[:personal].eql?(:cp_global)
      can :update, UserProfile, :user_id => user.id
    end
  end

end

ただし、次の単体テストでは次の結果が得られますtest_user_can_only_read_profile_with_personal_scope_set_to_public(AbilityTest): TypeError: can't convert Symbol into Integer

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

私はRubyとRailsに非常に慣れていません。Abilityモデルでprivacy_optionsキーの値をテストする適切な方法は何ですか?

4

1 に答える 1