Harry B.
Harry B.

Reputation: 421

Rspec Create Post with nested parameters

I'm trying to fix some tests that I have written in my comments controller. As of now, with my current tests I get this error:

Failure/Error: @outlet = Outlet.find(params[:comment][:outlet_id])

 ActiveRecord::RecordNotFound:
   Couldn't find Outlet with 'id'=

Here is an example of some of the tests

describe '#create' do
    context 'with valid attributes' do 
        before :each do
            @outlet = FactoryGirl.create(:outlet)
            @user = FactoryGirl.create(:user)
            @comment_params =  FactoryGirl.attributes_for(:comment)
        end

        let(:create) { post :create, params: { outlet_id: @outlet.id, user_id: @user.id, comment: @comment_params } }

        it "creates new comment" do
            expect { create }.to change { Comment.count }.by(1)
        end

        it "increases the post comment count by 1" do
            expect { create }.to change { @outlet.comments.count }.by(1)
        end

        it "increases user comment count by 1" do
            expect { create }.to change { @user.comments.count }.by(1)
        end
    end
end

I'm pretty sure this is happening because of my create statement in my tests

let(:create) { post :create, params: { outlet_id: @outlet.id, user_id: @user.id, comment: @comment_params } }

Here is my comments controller create action

def create
    @outlet = Outlet.find(params[:comment][:outlet_id])
    @comment = @outlet.comments.build(comment_params)
    @comment.user_id = current_user.id


    if @comment.save
        redirect_to(@outlet)
    end
end

I'm pretty sure it is not working, because the outlet_id that it is looking for is a nested parameter inside of the comments parameter. How would I fix my rspec test to have it look for a nested parameter?

Upvotes: 1

Views: 1526

Answers (1)

Mori
Mori

Reputation: 27779

Just pass your params as arguments to the post call, nesting as necessary, e.g.:

post :create, user_id: @user.id, comment: { outlet_id: @outlet.id }

Upvotes: 4

Related Questions