【问题标题】:Rspec ruby railsRspec 红宝石导轨
【发布时间】:2017-08-20 06:21:47
【问题描述】:

我正在尝试正确设置创建操作。

我不断收到错误消息:ArgumentError: Unknown keyword: topic

这里是测试:

require 'rails_helper'

RSpec.describe TopicsController, type: :controller do

let(:my_topic) { Topic.create!(name: RandomData.random_sentence, description: RandomData.random_paragraph)}
describe "POST create" do
it "increases the number of topics by 1" do
  expect{ post :create, {topic: {name: RandomData.random_sentence, description: RandomData.random_paragraph}}}.to change(Topic,:count).by(1)
end

it "assigns Topic.last to @topic" do
  post :create, { topic: {name: RandomData.random_sentence, description: RandomData.random_paragraph}}
  expect(assigns(:topic)).to eq Topic.last
end

it "redirects to the new topic" do
  post :create, {topic: {name: RandomData.random_sentence, description: RandomData.random_paragraph}}
  expect(response).to redirect_to Topic.last
end
end

这里是控制器:

  def create
@topic = Topic.new
@topic.name = params[:topic][:name]
@topic.description = params[:topic][:description]
@topic.public = params[:topic][:public]

if @topic.save
  redirect_to @topic, notice: "Topic was saved successfully."
else
  flash.now[:alert] = "Error creating topic.  Please try again"
  render :new
end
end

我正在尝试找出导致此错误的原因,我已经盯着它看了好几个小时,并尝试多次对其进行编辑但无济于事。我想不通。我一直在从事的项目的其余部分还可以,但是我无法弄清楚为什么我无法成功转换主题这个词。感谢您的观看。

【问题讨论】:

    标签: ruby-on-rails ruby rspec rspec-rails ruby-on-rails-5.1


    【解决方案1】:

    :topic 替换为:params。这是您测试的预期关键字。 RSpec 已经清楚您正在测试 Topic,因为您的规范文件是 TopicsController

    【讨论】:

      【解决方案2】:

      问题在于post 方法将关键字参数作为第二个参数。

      如果需要指定params,则应使用params关键字:

      post :create, params: { topic: { name: ..., description: ... } }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-04
        • 2018-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多