【发布时间】:2013-03-09 21:19:56
【问题描述】:
我正在尝试编写一个功能来测试用户模型的身份验证(设计 + cancan)。可以为用户分配不同的角色。关键是在经过身份验证的用户具有角色之一(“管理员”或“注册”)时测试功能。默认情况下,用户被创建为具有“已注册”角色。我使用rails3-devise-rspec-cucumber 和Authorization and users management in rails 作为开始。
所以我有以下表格
sqlite> .tables
roles_users users views
roles schema_migrations
app/model/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
before_save :setup_role
...
def setup_role
if self.role_ids.empty?
self.role_ids = 2 # corresponds to "registered"
end
end
end
app/model/role.rb
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
attr_accessible :name
end
features/user_authentication.feature
Scenario: User signs in successfully
Given I exist as a user
features/step_definitions/user_definition.rb
...
def create_user
create_visitor
delete_user
@user = FactoryGirl.create(:user, @visitor)
end
...
Given /^I exist as a user$/ do
create_user
end
spec/factories/user.rb
FactoryGirl.define do
factory :user do
email 'example@example.com'
password 'changeme'
password_confirmation 'changeme'
end
factory :role do
role_id 2
end
end
当我运行 cucumber 时,我得到 一个错误
Scenario: User signs in successfully # features/user_authentication.feature:12
Given I exist as a user # features/step_definitions/user_definition.rb:58
Couldn't find Role with id=2 (ActiveRecord::RecordNotFound)
./app/models/user.rb:21:in `setup_role'
我想我一定是错过了一些工厂或协会,但我是这个话题的新手,还没有设法找出解决问题的方法。我会很感激你的建议。
【问题讨论】:
标签: ruby-on-rails authentication devise cucumber cancan