2013-03-09 126 views
1

我正在尝试编写一个功能来测试用户模型(设计+康康)的身份验证。给用户可以归因于不同的角色。重点是在经过身份验证的用户具有其中一个角色(“admin”或“registered”)时测试功能。默认情况下,用户被创建为具有“已注册”角色。我使用rails3-devise-rspec-cucumberAuthorization and users management in rails作为开始。黄瓜设计

所以我有以下各表

sqlite> .tables 
roles_users  users     views   
roles    schema_migrations 

应用程序/模型/ 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 

应用程序/模型/ role.rb

class Role < ActiveRecord::Base 
    has_and_belongs_to_many :users 
    attr_accessible :name 
end 

功能/ user_authentication .feature

Scenario: User signs in successfully 
    Given I exist as a user 

功能/ 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 

规格/工厂/ user.rb

FactoryGirl.define do 
    factory :user do 
    email '[email protected]' 
    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' 

我想我必须错过一些工厂或协会,但我对这个话题很陌生,并且有n没有设法找出如何解决问题。我会感谢您的建议。

回答

0

你能你FactoryGirl定义修改为

FactoryGirl.define do 
    factory :user do 
    email '[email protected]' 
    password 'changeme' 
    password_confirmation 'changeme' 
    end 
    factory :role do 
    id 2 
    name 'registered' 
    end 
end 

Roleid,这成为role_id任何引用。所以你需要设置一个Role只需id