如何断言它以正确的 json 呈现?

How to assert it renders with the correct json?

我正在开发 JSON API 并正在尝试为 show 方法编写集成测试。问题是我不知道如何测试响应。下面我有 assert_response :success 但这条线似乎总是通过,即使它不应该通过(例如,当将 @author1 而不是 @article1 发布到 show_articles_path 时,这不应该没用)。

我应该使用什么断言行来测试它是否成功显示?

路线:

  show_articles POST   /articles/show/:id(.:format)         articles#show

测试:

  test "should get show" do
    post show_articles_path(@article1, article: {author_id: @author1.id })
    assert_response :success
  end

方法:

  def show
    @author = Author.find(params[:article][:author_id])
    article = Article.find(params[:id])
    render json: article
  end

我会使用 fixtures。在 test/fixtures 下创建一个文件夹并将您的文件放在那里。通常,我使用 ERB 模板,但很多人使用 YAML。这是一个简单的例子:

 <% bar ||= "bar's default value %>
 {
   "foo": "<%= bar %>",
   "baz": "quux"
 }

虽然 bar 有默认值,但您可以在加载夹具时对其进行参数化。您将代码中的响应主体与夹具中呈现的文本进行比较。

你也可以循环迭代:

 <% 1000.times do |n| %>
   "username": "<%= "user#{n}" %>"
   "email": "<%= "user#{n}@example.com" %>"
 <% end %>