我在Rails上运行了一些功能规范,由于某种原因,我无法使用role_model正确设置管理员。
这是我的代码:
应用/模型/ 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
应用/控制器/ 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
应用/规格/工厂/ 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
应用/规格/特征/ 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”失败,管理员用户应该登录。有人能告诉我我的设置是怎么回事吗?
答案 0 :(得分:2)
原来我必须删除管理工厂中的“=”。