【问题标题】:How to assert it renders with the correct json?如何断言它使用正确的 json 呈现?
【发布时间】:2016-01-18 18:50:19
【问题描述】:

我正在开发 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

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4 testing integration-testing


    【解决方案1】:

    我会使用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 %>
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多