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

时间:2018-12-20 03:04:06

标签: ruby-on-rails ruby rspec

我要检查创建动作是否通过。

 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

1 个答案:

答案 0 :(得分:4)

最可能是因为您正在使用的变量let!(:post)post :create, params: {post: post_params}post方法)冲突。

解决方案是将let!(:post)更改为let!(:posts),因为它仍然是列表。