【问题标题】:POST :create rspec controller testing error, wrong number of arguments 2 for 0POST:创建 rspec 控制器测试错误,参数数量错误 2 为 0
【发布时间】:2016-05-16 20:56:05
【问题描述】:

我正在尝试使用 rspec 在控制器规范中测试我的 Post_cmets#create 操作,但我不断收到以下错误消息:

 Failure/Error: post :create, :post_id => post.to_param, :post_comment => attributes_for(:post_comment, comment: "New")

 ArgumentError:
   wrong number of arguments (2 for 0)
 # ./spec/controllers/post_comments_controller_spec.rb:95:in `block (4 levels) in <top (required)>'

我的帖子评论控制器:

 class PostCommentsController < ApplicationController

  before_action :find_todo_list

  def index
    @post_comment = @post.post_comments.all
  end

  def show
    @post_comment = @post.post_comments.find(params[:id])
  end

  def new
    @post_comment = @post.post_comments.new
  end

  def edit
    @post_comment = @post.post_comments.find(params[:id])
  end

  def create
    @post_comment = @post.post_comments.new(post_comment_params)
    if 
      @post_comment.save
      redirect_to post_post_comments_path
      flash[:success] = "Comment added successfully!"
    else
      flash.now[:error] = "Comment could not be saved"
      render 'new'
    end
  end

  def update
    @post_comment = @post.post_comments.find(params[:id])
    if
      @post_comment.update(post_comment_params)
      redirect_to post_post_comment_path
      flash[:success] = "Comment successfully updated"
    else
      flash.now[:error] = "Comment could not be updated"
      render 'edit'
    end
  end

  def destroy
    @post_comment = @post.post_comments.find(params[:id])
    @post_comment.destroy

    redirect_to post_post_comments_path
    flash[:success] = "The comment was successfully deleted"
  end
end

private

  def find_todo_list
    @post = Post.find_by(params[:post_id])
  end

  def post_comment_params
    params.require(:post_comment).permit(:comment)
  end

我的控制器规格不断失败:

 describe "POST #create" do
context "flash messages" do
  let(:post) {create(:post)}

  it "sets flash success" do
    post :create, :post_id => post.to_param, :post_comment => attributes_for(:post_comment, comment: "New")
    expect(flash[:success]).to eq("Comment added successfully!")
  end
end

结束

我使用的是工厂女孩,所以这里是我的 post cmets 工厂,它与 post 有一个 belongs_to 关联...duh

  factory :post_comment do
    comment "Post comment"
    post
  end

任何帮助都会帮助我,谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby rspec controller


    【解决方案1】:
    let(:post) {create(:post)}
    # ...
    post :create
    

    let 是在当前 RSpec 示例中定义方法的一种奇特方式。 post 现在是一个接受 0 个参数的方法,因此消息 wrong number of arguments (2 for 0)

    尝试将您的 Post 对象命名为其他名称。

    【讨论】:

    • 非常感谢!这正是问题所在。 @zetetic
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-07
    相关资源
    最近更新 更多