【问题标题】:Using role_model and Factory_Girl (for spec testing), how do I properly setup a user as an admin?使用 role_model 和 Factory_Girl(用于规范测试),我如何正确地将用户设置为管理员?
【发布时间】:2013-07-11 20:40:19
【问题描述】:

我在 Rails 上运行一些功能规范,但由于某种原因,我无法使用 role_model 正确设置管理员。

这是我的代码:

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

由于某种原因,测试在管理员用户应该登录的“current_path.should eq admin_path”处一直失败。谁能告诉我我的设置发生了什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 testing rspec-rails


    【解决方案1】:

    原来我必须删除管理工厂中的“=”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2017-07-10
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多