我正在关注 Hartl 的 Rails 教程,但我使用了 devise/cancan/rolify,所以有些东西不一样。
在我的 users_pages_spec.rb 测试中,尽管我尝试了所有方法,但我仍然收到此错误:
1) User pages index delete links as an admin user
Failure/Error: sign_in @superadmin
NoMethodError:
undefined method `email' for nil:NilClass
# ./spec/support/utilities.rb:14:in `sign_in'
# ./spec/requests/user_pages_spec.rb:91:in `block (5 levels) in <top (required)>'
2) User pages index delete links as an admin user
Failure/Error: sign_in @superadmin
NoMethodError:
undefined method `email' for nil:NilClass
# ./spec/support/utilities.rb:14:in `sign_in'
# ./spec/requests/user_pages_spec.rb:91:in `block (5 levels) in <top (required)>'
3) User pages index delete links as an admin user should be able to delete another user
Failure/Error: sign_in @superadmin
NoMethodError:
undefined method `email' for nil:NilClass
# ./spec/support/utilities.rb:14:in `sign_in'
# ./spec/requests/user_pages_spec.rb:91:in `block (5 levels) in <top (required)>'
4) User pages index delete links as an admin user
Failure/Error: sign_in @superadmin
NoMethodError:
undefined method `email' for nil:NilClass
# ./spec/support/utilities.rb:14:in `sign_in'
# ./spec/requests/user_pages_spec.rb:91:in `block (5 levels) in <top (required)>'
我不明白为什么, nil::nilClass 是否意味着工厂女孩实际上无法创建这个超级管理员用户?
这是我的 user_pages_spec.rb 文件的示例:
require 'spec_helper'
require 'cancan/matchers'
# Test if targeted words appears in displayed content
describe "User pages" do
subject { page }
let(:user) { FactoryGirl.create(:user) }
let(:wrong_user) { FactoryGirl.create(:user, email: "wrong@example.com") }
let(:non_admin) { FactoryGirl.create(:user) }
let(:submit) { "Sign in" }
describe "index" do
describe "delete links" do
it { should_not have_link('delete') }
describe "as an admin user" do
let(:superadmin) { FactoryGirl.create(:superadmin) }
before do
sign_in @superadmin
visit users_path
end
it { should have_title('List of users') }
it { should have_link('delete', href: user_path(User.first)) }
it "should be able to delete another user" do
expect { click_link('delete') }.to change(User, :count).by(-1)
end
it { should_not have_link('delete', href: user_path(superadmin)) }
end
end
end
end
我的 spec/utilities.rb 定义了 sign_in 方法
include ApplicationHelper
def sign_in(user)
visit new_user_session_path
fill_in "Email", with: user.email
fill_in "Password", with: user.password
click_button "Login"
#populate cookie when not using capybara
cookies[:authentication_token] = user.authentication_token
end
和我的规范/工厂/user.rb
FactoryGirl.define do
factory :user do
sequence(:name) { |n| "Person #{n}" }
sequence(:email) { |n| "person_#{n}@example.com"}
password "beta"
password_confirmation "beta"
# required if the Devise Confirmable module is used
confirmed_at Time.now
confirmation_token nil
factory :superadmin do
after(:create) {|user| user.add_role(:superadmin)}
end
end
end
我确实在 cancan/rolify 中定义了超级管理员角色。
如果有人有线索,我会接受!如果还没有,我可以用需要的其他文件更新问题。