黄瓜设计

时间:2013-03-09 21:19:57

标签: ruby-on-rails authentication devise cucumber cancan

我正在尝试编写一个功能来测试用户模型的身份验证(设计+ cancan)。对用户可以归因于不同的角色。关键是在经过身份验证的用户具有其中一个角色(“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 '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'

我想我必须缺少一些工厂或协会,但我是这个主题的新手,并没有设法找出如何解决问题。我将非常感谢你的建议。

1 个答案:

答案 0 :(得分:0)

您可以将FactoryGirl定义更改为

FactoryGirl.define do
  factory :user do
    email 'example@example.com'
    password 'changeme'
    password_confirmation 'changeme'
  end
  factory :role do
    id 2 
    name 'registered'
  end
end

Roleid,在任何引用中都会变为role_id。因此,您需要使用Role设置id