使用Rails 4.2,rspec 2.14,rspec-rails 2.14,faker和factory-girls-rails gems
我有一个名为Appointment的模型,我正在运行一些测试,除了控制器规范下的#create外,一切都通过了。
我得到的错误信息是:
失败/错误:发布:创建,FactoryGirl.attributes_for(:约会) ActionController的:: ParameterMissing: param缺失或值为空:约会
Appointment模型验证是否存在与名为Service的对象的关联。
这是我的工厂预约.rb:
require 'faker'
FactoryGirl.define do
factory :appointment do |f|
f.service {FactoryGirl.create(:service)}
f.appointment_time { Faker::Time.between(DateTime.now - 1, DateTime.now) }
end
end
这是我的appointment_spec.rb:
require 'spec_helper'
describe Appointment do
it "has a valid factory" do
FactoryGirl.create(:appointment).should be_valid
end
it "is invalid if it does not have a Service association" do
FactoryGirl.build(
:appointment, service: nil).should_not be_valid
end
end
我一直按照here列出的说明制作我的控制器规格。我也发现很多stackoverflow帖子说要做同样的事情,但我仍然会得到同样的错误。
以下是未通过我的appointment_controller_spec.rb
的测试describe AppointmentsController do
#other controller action code...
describe "POST #create" do
context "with valid attributes" do
it "saves the new appointment in the database" do
expect {
post :create, FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
it "redirects to show page" do
post :create, FactoryGirl.attributes_for(:appointment)
response.should redirect_to Appointment.last
end
end
end
我不知所措,希望有人可以提供一些见解。
修改
正如你们有些人推荐的那样,我更改了控制器规格。这实际上是我在将代码更改为您在上面看到的内容之前所拥有的:
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
我改变这个的原因是因为当我有这个时我的原始错误信息是:
失败/错误:期望{ count应该已经被改变了1,但被改为0
很抱歉这个混乱。
答案 0 :(得分:2)
我相信你只需要你的AppointmentsController规范如下:
describe AppointmentsController do
#other controller action code...
describe "POST #create" do
context "with valid attributes" do
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end
it "redirects to show page" do
post :create, appointment: FactoryGirl.attributes_for(:appointment)
response.should redirect_to Appointment.last
end
end
end
在appointment:
调用中通过FactoryGirl提供属性之前添加post
。
答案 1 :(得分:1)
您是否在控制器中使用strong_params?看起来您正在寻找约会参数,但您只是获得了属性的哈希值。
试试这个:
it "saves the new appointment in the database" do
expect {
post :create, appointment: FactoryGirl.attributes_for(:appointment)
}.to change(Appointment, :count).by(1)
end