我的控制器上的参数丢失或值为空

时间:2017-10-29 00:32:46

标签: ruby-on-rails rspec factory-bot

我在rspec中有一个没有通过的测试,我不知道原因。该测试指责如下:

 1) SalesmenController POST #create redirect to new team
     Failure/Error: params.require(:salesmen).permit(:name, :company_id)

     ActionController::ParameterMissing:
       param is missing or the value is empty: salesmen

测试是:

    require 'rails_helper'

RSpec.describe SalesmenController, type: :controller do
   include Devise::Test::ControllerHelpers

   before(:each) do
    @request.env["devise.mapping"] = Devise.mappings[:owner]
    @current_owner = FactoryGirl.create(:owner)
    sign_in @current_owner
    @current_company = FactoryGirl.create(:company, owner: @current_owner)
  end

  describe "POST #create" do
    before(:each) do
      salesman = create(:salesman, company: @current_company)
      post :create, params: {:company_id => @current_company.id, company: { name: salesman.name, company_id: @current_company.id } }
    end

    it "redirect to new team" do
      expect(response).to have_http_status(:success)
    end

    it "Create team with right attributes" do
      expect(Salesman.last.company).to eql(@current_company)
      expect(Salesman.last.name).to eql(@salesman[:name])
    end
  end
end

我的控制器是:

def create
    @salesman = Salesman.new(params_salesman)
    authorize! :create, @salesman
    if @salesman.save
      redirect_to company_salesman_path
      flash[:notice] = "Salesman saved!"
    else
      flash.now[:error] = "Could not create salesman!"
      render :new
    end
  end

private

  def params_salesman
    params.require(:salesman).permit(:name, :company_id)
  end

我的路线是:

Rails.application.routes.draw do
  resources :companies do
    resources :salesmen
    resources :goals do
      resources :days
    end
  end
  devise_for :owners, :controllers => { registrations: 'registrations' }
end

我的工厂是:

FactoryGirl.define做  工厂:推销员    名称{FFaker :: Name.name}    公司  结束 端

任何人都知道会发生什么?

1 个答案:

答案 0 :(得分:0)

尝试使用params.permit(:name, :company_id)代替params.require(:salesman).permit(:name, :company_id)。原因是在您的测试环境中,您没有salesman进入您的参数。