【问题标题】:How to pass in extra params in RSpec Rails request spec如何在 RSpec Rails 请求规范中传递额外的参数
【发布时间】:2018-04-02 07:13:36
【问题描述】:

我还是一个初学者,所以我尝试做的可能不是最佳的,请随时提出更好的方法:

我正在尝试为关联用户创建合同。用户和authenticate_user 方法将被存根,但是RSpec 说它没有看到我在:contract_params 内部传递的参数中的user_id 外键。有人可以告诉我一种传递 user_id 以便 RSpec 识别它的方法吗? 谢谢!

spec/requests/contracts_api_spec.rb

RSpec.describe "ContractsApi", type: :request do

  describe "POST #create" do
    let (:contract_params) do
      {
        user: {
          vendor: "Lebara",
          starts_on: "2018-12-12",
          ends_on: "2018-12-16",
          price: "15",
          user_id: "8"
        }
      }
    end
    before(:each) do
      controller.stub(:authenticate_user)
    end

    it 'creates a new contract' do
      expect { post api_v1_user_contracts_path, params: contract_params }.to change(Contract, :count).by(1)
    end
  end
end

app/controllers/api/v1/contracts_controller.rb

class Api::V1::ContractsController < ApplicationController
  before_action :authenticate_user

  def create
    contract = @current_user.contracts.build(contract_params)
    if contract.save
      render json: contract
    else
      render json: contract.errors
    end
  end

  private

  def contract_params
    params.require(:contract).permit(:vendor, :starts_on, :ends_on, :price)
  end

【问题讨论】:

    标签: ruby-on-rails rspec parameters request


    【解决方案1】:

    阅读No route matches {:action=>"show", :controller=>"schools"} missing required keys: [:id]后,我意识到需要将user_id附加到url路径中,因此我通过以下更改成功:

    describe "POST #create" do
        let (:contract_params) do
          {
            vendor: "Lebara",
            starts_on: "2018-12-12",
            ends_on: "2018-12-16",
            price: "15",
          }
        end
        before(:each) do
          @user = User.create(full_name: "Jason Bourne", email: "jbourne@test.com", password: "123456")
          controller.stub(:authenticate_user)
        end
    
        it 'creates a new contract' do
          expect { post api_v1_user_contracts_path(@user), params: contract_params }.to change(Contract, :count).by(1)
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      相关资源
      最近更新 更多