Question: Rspec Error, create action in all models

Question

Rspec Error, create action in all models

Answers 1
Added at 2017-01-03 06:01
Tags
Question

My spec/controllers/undertakings_controller_spec.rb is below.

    require 'rails_helper'
    RSpec.describe UndertakingsController, type: :controller do
        describe '#create' do
         let(:undertaking_params) do
           attributes_for(:undertaking)
         end
         it 'increases undertaking by 1' do
              user=create(:user)
              login_user user
              expect{post :create , undertaking: undertaking_params }.to change(Undertaking, :count).by(1)
         end
       end
      end

I delete other actions in this spec file because the test of other actions works. and My controllers/undertakings_controller.rb is below.

      class UndertakingsController < ApplicationController
           def create
            @undertaking=current_user.undertakings.build(undertaking_params)
            @undertaking.asking_id=params[:asking_id]
           if @undertaking.save
             flash[:success] = "依頼の申し込みに成功しました。"
             redirect_to @undertaking.asking
           else
            @asking=@undertaking.asking
            render 'askings/show'
          end
        end

and My models/undertaking.rb is below.

      class Undertaking < ActiveRecord::Base
        belongs_to :user
        belongs_to :asking
        has_many :comments
        has_one :deciding
        validates :content , presence: true , length: {maximum: 800}
        validates :title , presence: true , length: {maximum: 20}
     end

My error is below.

       No route matches {:action=>"create", :controller=>"undertakings", :undertaking=>{:title=>"MyString", :content=>"MyText", :result=>false}}

Routes of the create action is below.

     asking_undertakings POST     /askings/:asking_id/undertakings(.:format)                   undertakings#create

I think maybe the error causes there is not :asking_id in spec file. But I can't understand what I should do. Please tell me.

Answers to

Rspec Error, create action in all models

nr: #1 dodano: 2017-01-03 06:01

As defined in your routes, your create path needs a asking_id to be passed as params. So, modifying your rspec line from

post :create , undertaking: undertaking_params

to

post :create, asking_id: <asking-id>, undertaking: undertaking_params

should work.

I see you are not creating an Asking in your rspec. So, you will first need to create one and then pass its id in the post :create call.

UPDATE

You can create Asking object in your rspec with factory-girl, given you have defined the factory for Asking model.

asking = create(:asking)
post :create, asking_id: asking.id, ...
Source Show
◀ Wstecz