在Rails(5.2(应用程序上运行测试时,我遇到了一些JSON解析器错误。这是一个例子:
错误[quot;testrongshould_show_photo",Minitest::Result,5.387737000361085]testrongshould_show_photo#小型测试::结果(5.39秒(Minitest::意外错误:ActionView::Template::错误:767:"MyText"处的意外令牌app/views/photos/show.html.erb:2:in>类中的
_app_views_photos_show_html_erb___4241643449401419846_70111557791480' test/controllers/photos_controller_test.rb:27:in
块:PhotosControllerTest‘
当在下面的代码中调用@photo实例变量时,错误发生在行中:
require 'test_helper'
class PhotosControllerTest < ActionDispatch::IntegrationTest
setup do
@photo = photos(:one)
end
test "should get index" do
get photos_url
assert_response :success
end
test "should get new" do
get new_photo_url
assert_response :success
end
test "should create photo" do
assert_difference('Photo.count') do
post photos_url, params: { photo: { image_data: @photo.image_data } }
end
assert_redirected_to photo_url(Photo.last)
end
test "should show photo" do
get photo_url(@photo)
assert_response :success
end
test "should get edit" do
get edit_photo_url(@photo)
assert_response :success
end
test "should update photo" do
patch photo_url(@photo), params: { photo: { image_data: @photo.image_data } }
assert_redirected_to photo_url(@photo)
end
test "should destroy photo" do
assert_difference('Photo.count', -1) do
delete photo_url(@photo)
end
assert_redirected_to photos_url
end
end
设置调用下面的yaml文件:
one:
image_data: MyText (This must be where the problem is)
two:
image_data: MyText
我认为这里的问题是MyText不是JSON语法,但我不知道如何更改它以使测试通过。
我找到了如何解决这个问题,我想带着解决方案回来,以防它能帮助其他人
事实上,问题是默认的scaffold generate.yml文件不是有效的json。
我想出的解决方案是从我之前成功保存的数据库中复制并粘贴一条记录。我打开Rails控制台,查找了一个有效的照片记录,并用单引号括起来:
one:
image_data: '{"id":"164214a2b7a969102f90edadccaae62b.jpg","storage":"store","metadata":{"filename":"changes.jpg","size":24434,"mime_type":"image/jpeg"}}'
之后,所有失败的测试都通过了。