首页 > 解决方案 > JSON::ParserError: 767: 'MyText' 中的意外令牌(Rails & Minitest)

问题描述

我在 Rails (5.2) 应用程序上运行测试时遇到一些 JSON 解析器错误。这是一个例子:

错误 ["test_should_show_photo", Minitest::Result, 5.387737000361085] test_should_show_photo#Minitest::Result (5.39s) Minitest::UnexpectedError: ActionView::Template::Error: 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

setup调用下面的 yaml 文件:

one:
  image_data: MyText (This must be where the problem is)

two:
  image_data: MyText

我认为这里的问题是MyText不是 JSON 语法,但我不知道如何更改它以使测试通过。

标签: ruby-on-railsruby-on-rails-5

解决方案


我想出了如何解决这个问题,我想返回解决方案,以防它可以帮助其他人。

问题确实是默认的脚手架生成 .yml 文件不是有效的 json。

我想出的解决方案是从我之前成功保存的数据库中复制并粘贴一条记录。我打开 Rails 控制台并查找照片的有效记录并将其用单引号括起来:

one:

image_data: '{"id":"164214a2b7a969102f90edadccaae62b.jpg","storage":"store","metadata":{"filename":"changes.jpg","size":24434,"mime_type":"image/jpeg"}}'

之后,所有失败的测试都通过了。


推荐阅读