Rails / Rspec / Factory girl:记录无关联?

时间:2012-03-12 02:12:53

标签: ruby-on-rails rspec factory-bot

这是我的工厂:

FactoryGirl.define do
  factory :account do
    company 'Example, Inc.'
  end

  factory :site do
    association :account
  end

  factory :page do
    association :site
  end
end

一个简单的请求规范:

require 'spec_helper'

describe "Pages" do

  before do
    @account = Factory(:account)
    @site = Factory(:site)
  end

  it "lets me create a new page" do
    visit account_site_pages_path(@account, @site)
    page.should have_content('New Page')
  end

end

但是我失败了:

Failure/Error: visit account_site_pages_path(@account, @site)
ActiveRecord::RecordNotFound:
 Couldn't find Site with ID=51 [WHERE (`sites`.account_id = 127)]
# <internal:prelude>:10:in `synchronize'
# ./spec/requests/pages_spec.rb:19:in `block (2 levels) in <top (required)>'

意味着网站工厂与正确的帐户无关,对吧?我猜我错过了一些非常明显的东西:D

1 个答案:

答案 0 :(得分:0)

您的@account@site未连接,这可能是问题所在。所以:

before do
  @account = Factory(:account)
  @site = Factory(:site, :account => @account)
end

这样,您的网站就不会创建新帐户,而是与原始帐户相关。