无法弄清楚为什么工厂女孩不会为我生成我的问题ID。
工厂:
用户:
require 'faker'
FactoryGirl.define do
factory :user do
email {Faker::Internet.email}
name {Faker::Name.name}
password '12345678'
password_confirmation '12345678'
end
end
的问题:
require 'faker'
FactoryGirl.define do
factory :question do
association :user
title "Random question about Ruby on Rails"
body { Faker::Lorem.paragraph(2) }
end
end
特征测试
require 'spec_helper'
feature "Show questions" do
given(:user) { FactoryGirl.create(:user) }
given(:question) { FactoryGirl.build(:question, user_id: user.id) }
scenario 'guest user cannot visit edit question path' do
visit edit_question_path(question)
expect(current_url).to eq root_url
end
...
end
终端失败:
ActionController::UrlGenerationError:
No route matches {:action=>"edit", :controller=>"questions", :format=>nil,
:id=>#<Question id: nil, title: "Random question about Ruby on Rails",
body: "Dolor in doloribus labore. Totam debitis eveniet v...", created_at: nil, updated_at: nil, user_id: 6309>} missing required keys: [:id]
我知道解决方案就在那里,但我无法理解这个问题。谢谢!
答案 0 :(得分:2)
使用build
创建一个没有数据库ID的内存对象
FactoryGirl.build(:question, user_id: user.id)
使用create
将在数据库中使用id
FactoryGirl.create(:question, user_id: user.id)
您当前的代码正在尝试进入从未保存的Question
的编辑页面