Yorkshireman
Yorkshireman

Reputation: 2343

Rspec having difficulty testing #create with build controller method

So if your #create controller method is simply:

@testimonial = Testimonial.new(testimonial_params)

And you test it in your specs like so:

testimonials_controller_spec.rb

describe "POST #create" do 
    context "with VALID attributes" do 
        it "creates new testimonial" do 
            expect {
                    post :create, testimonial: FactoryGirl.attributes_for(:testimonial)
            }.to change(Testimonial, :count).by(1)
        end
    end
end

It works fine. The code:

post :create, testimonial: FactoryGirl.attributes_for(:testimonial)

is correct.

However, in my TestimonialsController, my create method is actually:

@testimonial = current_user.testimonials.build(testimonial_params)

My rspec method doesn't work with this. What should I use instead of:

post :create, testimonial: FactoryGirl.attributes_for(:testimonial)

?

Upvotes: 0

Views: 88

Answers (2)

sufinsha
sufinsha

Reputation: 765

Sign in the user before calling the controller action. Please find the following:

#testimonials_controller_spec.rb 
require 'rails_helper' 
describe TestimonialsController, type: :controller do

  let(:user) do
    FactoryGirl.create :user
  end

  before do
    sign_in user
  end

  describe "POST #create" do 
    context "with VALID attributes" do 
      it "creates new testimonial" do 
        expect {
          post :create, testimonial:    FactoryGirl.attributes_for(:testimonial)
        }.to change(Testimonial, :count).by(1)
      end
    end
  end
end

Upvotes: 3

Jimmy Baker
Jimmy Baker

Reputation: 3255

Build doesn't save/persist the record to the database. Why not make it:

@testimonial = current_user.testimonials.new(testimonial_params)
@testimonial.save

Upvotes: -1

Related Questions