ユーザーモデルの認証をテストする機能を作成しようとしています(devise + cancan)。ユーザーには、さまざまな役割を割り当てることができます。重要なのは、認証されたユーザーがいずれかの役割("admin"または"registered")を持っているときに機能をテストすることです。デフォルトでは、ユーザーは「登録済み」の役割を持つものとして作成されます。まず、 rails3 -devise-rspec-cucumberとAuthorization and users managementinrailsを使用しています。
だから私は次のテーブルを持っています
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 / factorys / 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
きゅうりを走らせるとエラーになります
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'
私はいくつかの工場や協会が欠けているに違いないと思いますが、私はこのトピックに不慣れで、問題を解決する方法を見つけることができませんでした。アドバイスをいただければ幸いです。