4

好的,所以我想测试需要管理员用户的功能,我正在尝试以管理员身份登录,但为了做到这一点,我需要有管理员用户

这是我的代码

  let(:user) { FactoryGirl.create(:user) }
  let(:admin_role) { FactoryGirl.create(:role) }

FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    email  "john@doe.com"
  end

  factory :role do
    name "Admin"
  end
end

我如何连接它们我试过 user.roles << user_role但得到了这个错误

/Users/matt/Sites/application/spec/controllers/directory_controller_spec.rb:16:in `block (3 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x007fa550890d80> (NameError)

这是我的模型

class User < ActiveRecord::Base
    has_many :roles, :through => :role_users
    has_many :role_users
    ...

class Role < ActiveRecord::Base
    has_many :users, :through => :role_users
    has_many :role_users
    ...

class RoleUser < ActiveRecord::Base
    belongs_to :role
    belongs_to :user
end
4

3 回答 3

8

spec/factories/user.rb

FactoryGirl.define do
  factory :user do
    first_name "John"
    last_name  "Doe"
    email "john@doe.com"
  end

  factory :admin_user, :parent => :user do
    roles { [ FactoryGirl.create(:admin_role) ] }
  end

  factory :role do
    name { "Role_#{rand(9999)}" }
  end

  factory :admin_role, :parent => :role do
    name "Admin"
  end
end
于 2012-04-12T21:05:39.660 回答
0

我遇到了完全相同的问题,代码如下:

describe "..." do
  let(:user) { create :user }
  let(:manager) { create :manager_role }
  user.roles << manager

  it "should ...." do
    # etc.
  end

end

# run rspec...
# => `block (2 levels) in <top (required)>': undefined local variable or method `user' for #<Class:0x000001016a2dc0> (NameError)

当我将user.roles << manager代码移动到一个before(:each)块中时,错误消失了。因此,类似:

describe "..." do
  let(:user) { create :user }
  let(:manager) { create :manager_role }

  before(:each) do
    user.roles << manager
  end

  it "should ...." do
    # etc.
  end

end

role <-> user这省去了必须在工厂中指定关联的痛苦。

我对 rspec 和 factory_girl 的工作方式不够熟悉,无法理解为什么不能user.roles << role在 call 之后立即拥有代码let(:user) { create :user },但是将其放入before(:each)块或单个it "should ... " do块中应该可以解决问题。

于 2012-05-10T17:56:51.213 回答
0

解决了

Factory.sequence(:email) {|n| "person#{n}@example.com" }

Factory.define :role do |r|
  r.name {"Admin"}
end

Factory.define :role_user do |ru|
  ru.association(:role)
  ru.association(:user)
end

Factory.define :user do |u|
  u.first_name {"matt"}
  u.last_name {"jones"}
  u.email {Factory.next(:email)}
end

并像使用它一样

  let(:role_user) { FactoryGirl.create(:role_user)  }
  before { sign_in(role_user) }
于 2012-04-13T14:39:32.560 回答