我正在尝试在我的控制器中添加FactoryGirl支持默认的脚手架规格,但我似乎无法找到正确的语法。
以下是一个示例测试:
describe "POST create" do
describe "with valid params" do
it "creates a new Course" do
expect {
post :create, {:course => valid_attributes}, valid_session
}.to change(Course, :count).by(1)
end
do
我替换为:
describe "POST create" do
describe "with valid params" do
it "creates a new Course" do
expect {
post :create, course: FactoryGirl.build(:course)
}.to change(Course, :count).by(1)
end
do
规格/工厂/ courses.rb
FactoryGirl.define do
factory :course do
association :provider
name "Course name"
description "course description"
end
end
应用程序/模型/ course.rb
class Course < ActiveRecord::Base
validates :name, :presence => true
validates :description, :presence => true
validates :provider_id, :presence => true
has_many :terms
belongs_to :provider
end
应用程序/控制器/ courses_controller.rb
# POST /courses
# POST /courses.json
def create
@course = Course.new(course_params)
respond_to do |format|
if @course.save
format.html { redirect_to @course, notice: 'Course was successfully created.' }
format.json { render action: 'show', status: :created, location: @course }
else
format.html { render action: 'new' }
format.json { render json: @course.errors, status: :unprocessable_entity }
end
end
end
它通常会失败:“ActionController :: ParameterMissing:param not found:course”有没有人有任何想法?
谢谢! 弗朗西斯
答案 0 :(得分:11)
尝试:
describe "POST create" do
describe "with valid params" do
it "creates a new Course" do
expect {
post :create, course: FactoryGirl.attributes_for(:course, provider_id: 1)
}.to change(Course, :count).by(1)
end
end
end
Factory Girl使用attributes_for
选项生成值的哈希,而不是Ruby对象。