控制器规范中的参数数量错误(给定2,预期为0)

问题描述 投票:0回答:1

我想检查创建操作是否通过。

 describe "#create" do
  let!(:user){ create(:user) }
  let!(:post){ create_list(:post, 3, user: user) }
    context "authenticated user" do
      it "adds a new post" do   
        post_params = FactoryBot.attributes_for(:post)
        sign_in user  
        expect{ post :create, params: {post: post_params} }.to change(user.posts, :count).by(1)
      end
    end
  end

但我的错误是

Failure/Error: expect{ post :create, params: {post: post_params} }.to change(user.posts, :count).by(1)

     ArgumentError:
       wrong number of arguments (given 2, expected 0)

posts_controller:

def create
    @post = Post.new(post_params)
    if params[:images]
      if @post.save
        params[:images].each do |img|
          @post.photos.create(image: img)
        end
      else
      end
      redirect_to posts_path
      flash[:notice] = "success"
    else
      redirect_to posts_path
      flash[:alert] = "failure"
    end
  end
ruby-on-rails ruby rspec
1个回答
4
投票

这很可能是因为你使用的变量let!(:post)post :create, params: {post: post_params}post方法)发生冲突。

解决方案是将let!(:post)更改为let!(:posts),因为无论如何它都是一个列表。

© www.soinside.com 2019 - 2024. All rights reserved.