我还是初学者,所以我想做的可能不是最佳的,随意提出更好的方法:
我正在尝试测试为关联用户创建合约。用户和authenticate_user方法将被存根,但是RSpec说它没有在我传入的params中传递的user_id外键:contract_params。有人可以告诉我传递user_id的方法,以便RSpec识别它吗? 谢谢!
规格/请求/ 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
应用程序/控制器/ 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
答案 0 :(得分:0)
阅读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