简体   繁体   中英

Using role_model and Factory_Girl (for spec testing), how do I properly setup a user as an admin?

I'm running some feature specs on Rails and for some reason I can't get an admin properly setup using role_model.

Here's my code:

app/models/user.rb

   class User < ActiveRecord::Base
      include RoleModel

      attr_accessible :email, :username, :roles, :password, :password_confirmation

      has_secure_password
      validates :email, :username, :password, :password_confirmation, presence: true
      validates :email, :username, uniqueness: true

      roles :admin, :moderator, :developer
    end

app/controllers/sessions_controller.rb

class SessionsController < ApplicationController
...
    def create
        user = User.find_by_email(params[:email])
        if user && user.authenticate(params[:password])
            session[:user_id] = user.id
            if user.is? :admin
                redirect_to admin_url, notice: "Admin Logged In!"
            else 
                redirect_to user_url(user), notice: "Logged In!"
            end
        else
            flash.now.alert = "Email or password invalid!"
            render "new"
        end
    end

...
end

app/spec/factories/users.rb

require 'faker'
require 'role_model'

FactoryGirl.define do 
    factory :user do
        username { Faker::Internet.user_name }
        email { Faker::Internet.email }
        password "password"
        password_confirmation "password"

        factory :invalid_user do
            username nil
        end

        factory :admin do
            roles = [:admin]
        end
    end
end

app/spec/features/admin_spec.rb

require "spec_helper"

feature "Admin Dashboard" do
    scenario "accesses the dashboard" do
        admin = create(:admin)

        visit root_path
        fill_in "Email", with: admin.email
        fill_in "Password", with: admin.password
        click_button "Login"

        current_path.should eq admin_path
        within 'h1' do
            page.should have_content "Hello, world!"
        end

        page.should have_content @app_name
        page.should have_content "Games"
    end
end

For some reason the test keeps failing at "current_path.should eq admin_path" where the admin user should be logged in. Can anyone tell me what's going on with my setup?

结果我不得不删除管理工厂中的“=”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM