工厂女孩rspec问题:has_many通过工厂

时间:2017-04-18 18:02:15

标签: ruby-on-rails ruby rspec ruby-on-rails-5 factory-bot

我在Rails中遇到有关Factory Girl的问题。我目前有专家设置我试图测试我的用户政策但工厂在rspec时似乎不起作用。

在rails控制台中,我可以加载控制台并输入:

    user=FactoryGirl.create(:admin_user)
    r=user.roles

这可以正确地创建用户以及用户和角色之间的正确关联。但是,在rspec中使用工厂时 - 创建用户但不创建关联的分配。 (我通过在特定测试中使用' pp'发现了这一点。)

我不需要创建角色,因为角色已设置好所以我正在查找它们。

有什么想法吗?

模型

    class User < ApplicationRecord
     has_many :assignments, dependent: :destroy
     has_many :roles, through: :assignments, dependent: :destroy

      def has_role?(roles)
        roles.each do |role|
          if self.roles.include? role
            return true
          end
        end

        false
      end

    class Role < ApplicationRecord
      # Associations
      has_many :assignments
      has_many :users, through: :assignments

    class Assignment < ApplicationRecord
      # Associations
      belongs_to :user
      belongs_to :role

工厂

    FactoryGirl.define do
      factory :user do
        first_name  {Faker::Name.first_name}
        last_name   {Faker::Name.last_name}
        email       {Faker::Internet.email}
        password    {Faker::Internet.password(8)}

          factory :admin_user do
                after(:create) do |user|
                Assignment.create(user: user , role: Role.find_by(label:'System Admin') )
            end
          end

      end
    end

测试

用户政策测试

    describe UserPolicy do
      subject { UserPolicy }

       let (:current_user) { FactoryGirl.build_stubbed :user}
       let (:other_user) { FactoryGirl.build_stubbed :user }
       let (:admin) { FactoryGirl.build_stubbed :admin_user}


      permissions :index? do
        it "denies access if not an admin" do
          expect(UserPolicy).not_to permit(current_user)
        end
        it "allows access for an admin" do
          expect(UserPolicy).to permit(admin)
        end
      end
    end

具有相同问题的其他测试

    feature 'User index page', :devise do

      after(:each) do
        Warden.test_reset!
      end

      scenario 'user sees own email address' do
        user = FactoryGirl.create(:admin_user)
        expect(user.has_role?(Role.where(label: 'System Admin'))).to eq true
        login_as(user, scope: :user)
        visit users_path
        expect(page).to have_content user.email
      end

    end

此测试失败,因为用户没有分配角色。

控制器

    class AssignmentsController < ApplicationController
      def create
        @assignment = Assignment.new(assignment_params)
        if @assignment.save
          redirect_to users_path(), :notice => "Role Added"
        else
          flash[:alert]="Unable to Add Role"
        end
      end

0 个答案:

没有答案