RSpec测试创建文章接口报错:ActionController::ParameterMissing
错误原因与解决方法
错误原因
Rails控制器的强参数机制要求创建文章的参数必须嵌套在article键下,你的测试代码直接传递了平级的name和post_id参数,不符合控制器期望的参数结构,因此触发了ParameterMissing错误。
解决方法
1. 修正测试参数结构
将参数嵌套到article键内,同时统一变量引用方式(避免实例变量和let变量混用):
RSpec.describe 'Api::V1::Articles', type: :request do ... describe 'POST /create' do context "valid" do let(:test_post) { Post.create!(title: "测试文章") } # 提前创建测试用的Post实例 let(:articles_params) { { article: { # 把参数嵌套到article键下 name: "art", post_id: test_post.id } } } it 'creates a new article' do expect { post "/api/v1/posts/#{test_post.id}/articles", params: articles_params }.to change(Article,:count).by(1) end end end
2. 确认控制器强参数配置
确保你的Api::V1::ArticlesController中存在正确的强参数方法:
private def article_params params.require(:article).permit(:name, :post_id) end
内容的提问来源于stack exchange,提问作者register
相关产品推荐
相关产品推荐

