【发布时间】:2018-04-02 00:00:04
【问题描述】:
我想查看用户是否有权访问我的应用程序中的某些页面。为此,我使用rSpec 和FactoryBot 作为我的固定装置替代品。
我有两个工厂,一个用于role 的has_many 用户,一个用于user 的belongs_to 一个role。
角色工厂
FactoryBot.define do
factory :role do
trait :admin do
role_name 'admin'
end
end
factory :admin, traits: [:admin]
end
用户工厂
FactoryBot.define do
factory :user do
association :role, factory: :admin
end
end
我正在使用 Pundit 进行授权,并使用 Pundit Matchers gem 来测试 Pundit 政策。
需要'rails_helper'
describe AccountPolicy do
subject { described_class.new(user, account) }
let (:account) { Account.create }
context 'being an admin' do
let(:user) { User.create(role: :admin) }
it { is_expected.to permit_action([:index]) }
end
end
以上是为查看作为管理员的用户是否可以访问帐户索引而编写的策略。运行rake 时出现以下错误。
ActiveRecord::AssociationTypeMismatch:
Role(#70284397401400) expected, got :admin which is an instance of Symbol(#70284363589400)
我发现我遇到了类型不匹配。但是,我不确定如何将角色作为活动记录对象返回,我认为这是它的外观所期望的,而不是符号。我怎样才能做到这一点?
【问题讨论】:
标签: ruby-on-rails rspec factory-bot pundit