目前正在使用 minitest-rails 进行Rails单元测试。
我正在使用 bootstrap editable js 来直接更新视图中的数据。
我无法正确判断值,导致失败结果。
仅用于我使用 bootstrap editable 的功能,因为它使用其他方式发送参数而不是正常的Rails更新操作。
请帮助查看我的代码。
在我的控制器:
中def edit_job_type
update_common_table('job_types', params[:pk], params[:name], params[:value])
end
在我的附带模块:
中def update_common_table(table, id, key, value)
begin
case table
when 'job_types'
@record = JobType.find(id)
end
case key
when 'en_name'
@record.en_name = params[:value]
edit_field = 'English Name'
end
@record.last_updated_by = session[:username]
@record.save
render json: {
status: 'success',
message: "#{edit_field} was successfully updated.",
updated_at: @record.updated_at.to_time.strftime("%a, %e %b %Y %H:%M"),
updated_by: session[:username]
}
rescue => error
render json: {status: 'error', message: error.message}
end
end
在我的 minitest-rails ,控制器中:
setup do
@job_type = job_types(:waiter)
end
test "should update job_type" do
patch :edit_job_type, id: @job_type.id, job_type: { pk: @job_type.id, name: 'en_name', value: "janitor" }
assert_response :success, message: 'English Name was successfully updated.'
@job_type.reload
assert_equal "janitor", @job_type.en_name # this one FAILS, not updated value
end
在我的灯具>中job_types :
waiter:
en_name: waiter
当我运行 rake test 时:
I got failure result, because the update was failed.
Expected: "New Job Type Updated"
Actual: "waiter"
Still getting the default value "waiter", instead of "janitor"
请帮助弄清楚如何修复我的测试。
答案 0 :(得分:0)
<强>解决强>
最后,经过彻底的搜索,我做了一个工作。
解决方案是使用XHR方法,因为bootstrap editable使用POST方法。
<强>之前强>:
test "should update job_type" do
patch :edit_job_type, id: @job_type.id, job_type: { pk: @job_type.id, name: 'en_name', value: "janitor" }
assert_response :success, message: ' Successfully updated.'
@job_type.reload
assert_equal "janitor", @job_type.en_name # this one FAILS, not updated value
end
<强>后强>:
test "should update job_type" do
xhr :post, :edit_job_type, format: :js, pk: @job_type.id, name: 'en_name', value: "janitor"
assert_response :success, ' Successfully updated.'
@job_type.reload
assert_equal "janitor", @job_type.en_name
end
感谢本教程Building Rails Test