1

我是 RSpec 的新手,我有以下代码。

class User < ActiveRecord::Base
  attr_accessible :email, :name, :admin, :active, :password, :password_confirmation

  has_many :venues
  has_many :events
  ...
end

class Venue < ActiveRecord::Base
  attr_accessible :name, :url, :street, :city, :state, :description, :user_id

  belongs_to :user
  ...
end

FactoryGirl.define do
  factory :user do
    sequence(:name) { |n| "Person #{n}"}
    sequence(:email) { |n| "foo#{n}@example.com"}
    password "secret"
    password_confirmation "secret"

    factory :admin do
      admin true
    end

    factory :active_user do 
      active true
    end
  end 

  factory :venue do
    sequence(:name) { |n| "Venue #{n}"}
    sequence(:url) { |n| "mail@venue#{n}"}
    sequence(:street) { |n| "#{n} Main St."}
    city "Chicago"
    state "IL"
  end
end

在我的测试中,我想创建一个设置为的venue对象,但以下内容不起作用:user_iduser.id

describe "as active user" do
  let(:active_user) { FactoryGirl.create(:active_user) }
  let(:user_venue) { FactoryGirl.create(:venue, user: active_user) }
  let(:other_venue) { FactoryGirl.create(:venue) }
4

1 回答 1

0

尝试将您的场地工厂更改为

# rspec/factories/venue.rb
FactoryGirl.define do
  factory :venue do
    sequence(:name) { |n| "Venue #{n}"}
    sequence(:url) { |n| "mail@venue#{n}"}
    sequence(:street) { |n| "#{n} Main St."}
    city "Chicago"
    state "IL"
    user
  end
end

并以这种方式在您的规范中使用它

describe "as active user" do
   let(:active_user) { FactoryGirl.create(:active_user) }
   let(:user_venue) { FactoryGirl.create(:venue, user_id: active_user.id) }
   ...
end
于 2013-07-28T01:07:20.213 回答