使用 Rspec 测试注释控制器时出现错误数量的参数错误

wrong number of arguments error while testing comments controller using Rspec

在测试评论控制器时,我在创建评论时遇到此错误。

Failures:

  1) CommentsController Valid POST create creates a new comment
     Failure/Error: post :create, params: { comment: { content: 'TestCommentContent' }, topic_id: topic.id, post_id: post.id }

     ArgumentError:
       wrong number of arguments (given 2, expected 0)
     # ./spec/controllers/comments_controller_spec.rb:10:in `block (5 levels) in <top (required)>'
     # ./spec/controllers/comments_controller_spec.rb:9:in `block (4 levels) in <top (required)>'

Finished in 0.15835 seconds (files took 13.89 seconds to load)

这是我的 CommentsController rspec 代码:

require 'rails_helper'

RSpec.describe CommentsController, type: :controller do
  describe 'Valid' do
    let!(:topic) { Topic.create(title: 'test_Post_topic_title', name: 'test_Post_topic_name') }
    let!(:post) { Post.create(title: "TestPostTitle1", content: "TestPostContent1", topic_id: topic.id) }
    context 'POST create' do
      it 'creates a new comment' do
        expect do
          post :create, params: { comment: { content: 'TestCommentContent' }, topic_id: topic.id, post_id: post.id }
        end.to change(Comment, :count).by(1)
        expect(assigns(:comment).content).to eql "'TestCommentContent"
        expect(flash[:notice]).to match('Comment was successfully created.')
        expect(response).to redirect_to "/topics/#{assigns(:topic).id}/posts/#{assigns(:post).id}"
        expect(response).to have_http_status(:found) #302
      end
    end
end

在开发环境中,当我创建评论时,这是已创建的日志:

Started POST "/topics/3/posts/12/comments" for ::1 at 2021-05-13 14:01:49 +0530
Processing by CommentsController#create as HTML
  Parameters: {"authenticity_token"=>"[FILTERED]", "comment"=>{"content"=>"Yummy!!"}, "commit"=>"Create Comment", "topic_id"=>"3", "post_id"=>"12"}
  Topic Load (0.4ms)  SELECT "topics".* FROM "topics" WHERE "topics"."id" = ? LIMIT ?  [["id", 3], ["LIMIT", 1]]
  ↳ app/controllers/comments_controller.rb:59:in `get_topic_id'
  Post Load (0.5ms)  SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ?  [["id", 12], ["LIMIT", 1]]
  ↳ app/controllers/comments_controller.rb:63:in `get_post_id'
  TRANSACTION (0.1ms)  begin transaction
  ↳ app/controllers/comments_controller.rb:8:in `create'
  Comment Create (112.8ms)  INSERT INTO "comments" ("post_id", "content", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["post_id", 12], ["content", "Yummy!!"], ["cr
eated_at", "2021-05-13 08:31:49.791154"], ["updated_at", "2021-05-13 08:31:49.791154"]]
  ↳ app/controllers/comments_controller.rb:8:in `create'
  TRANSACTION (1191.9ms)  commit transaction
  ↳ app/controllers/comments_controller.rb:8:in `create'
Redirected to http://localhost:3000/posts/12
Completed 302 Found in 1354ms (ActiveRecord: 1305.7ms | Allocations: 4639)

我必须为此发送 3 个参数,但它说预期参数为 0。??如何解决这个问题。 提前致谢...!!!

您已经用 let! 定义了 post,它隐藏了发送请求的 post 方法。想出另一个名字。