2013-03-09 129 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