我正在尝试为控制器编写测试。“创建”操作需要表单数据,如果表单数据不符合要求,则会被拒绝为“无法处理的实体”:
Failure:
ContactsControllerTest#test_should_post_create [test/controllers/contacts_controller_test.rb:36]:
Expected response to be a <3XX: redirect>, but was a <422: Unprocessable Entity>
我在下面包括了模型、控制器、测试控制器和装置。授权仍然是开箱即用的,但在这里不应该成为因素(其他测试运行良好)。
我怀疑参数中的外键是罪魁祸首,但我不知道如何检查。我还在测试参数中尝试了@saluation.id 和@debitor.id。
模型
class Contact < ApplicationRecord
validates :last_name, presence: true
validates :email, format: {
with: URI::MailTo::EMAIL_REGEXP
}
belongs_to :salutation
belongs_to :debitor
控制器
class ContactsController < ApplicationController
def create
@contact = Contact.new(contact_params)
@debitors = Debitor.all
@salutations = Salutation.all
if @contact.save
redirect_to contacts_path
else
render :new, status: :unprocessable_entity
end
end
private
def contact_params
params.require(:contact).permit(:last_name, :first_name, :email, :salutation_id, :debitor_id)
end
end
测试
require "test_helper"
class ContactsControllerTest < ActionDispatch::IntegrationTest
setup do
@user = users(:lazaro_nixon)
@contact = contacts(:one)
@salutation = salutations(:one)
@debitor = debitors(:one)
end
test "should post create" do
sign_in_as @user
post contacts_url, :params => { :contact => { last_name: "Lastname", first_name: "Firstname", email: "[email protected]", salutation: @salutation, debitor: @debitor }}
assert_response :redirect
follow_redirect!
assert_response :success
end
end
装置 - 接触器
one:
last_name: MyString
first_name: MyString
email: MyString
salutation: one
debitor: one
固定装置 - 致意
one:
salutation: MyString
固定装置 - 债务人
one:
company: MyString
street: MyString
house_number: MyString
zip: 1
city: MyString
payment_terms: one
我认为你的测试参数键应该
salutation_id
是debitor_id
您需要传递记录的 id 而不是整个记录,并使用与预期参数相同的键名。
但测试可以稍加改进,以便真正测试控制器操作的重要方面。
这将测试该记录是否真正创建以及位置是否是最后创建的记录,而不仅仅是控制器将您重定向到任意路径,这会让您很容易受到误报的影响。