【发布时间】: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