You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用RSpec编写更新测试?遇ArgumentError错误求助

RSpec更新测试参数错误解决办法

你的测试代码存在几个问题,直接引发了ArgumentError错误:

问题代码

describe 'PUT /update' do
  context "update a Article" do
    it 'update ' do
      put "/api/v1/posts/#{@post.id}/articles/#{@article.id}", article =>{name: "n"}
      expect { @patient.name }.to eq("ABCD1")
    end
  end
end

报错信息

ArgumentError:
       unknown keyword: #<Article id: 1,

错误原因及修正步骤

  1. 参数键名错误:article =>{name: "n"}里的article是你定义的实例对象,不是哈希键名,应该用符号:article或Ruby关键字参数写法article:来指定参数命名空间。
  2. 笔误与语法错误:expect { @patient.name }里的@patient是笔误,应为@article;同时expect不需要用块包裹,且必须重新从数据库读取更新后的数据,否则内存中的实例不会同步变更。
  3. Rails请求参数规范:Rails API推荐用params:关键字传递参数,确保参数格式符合框架要求。

修正后的代码

describe 'PUT /update' do
  context "update an Article" do
    it 'updates the article name' do
      put "/api/v1/posts/#{@post.id}/articles/#{@article.id}", params: { article: { name: "n" } }
      @article.reload # 重新加载数据库中更新后的记录
      expect(@article.name).to eq("n")
    end
  end
end

如果你的Rails版本不支持params:关键字参数,可改用哈希传递:

put "/api/v1/posts/#{@post.id}/articles/#{@article.id}", { article: { name: "n" } }

额外说明

  • 测试描述尽量准确,把update 改成updates the article name更清晰。
  • 必须调用@article.reload,否则内存中的实例不会自动同步数据库的更新内容。
  • 确保@post和@article已经在测试前置的before块中正确创建并赋值。

内容的提问来源于stack exchange,提问作者register

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:01:03