Question

I have problem with testing my controller. I've test post request in 2 context. With valid attributes and with invalid attributes. I have problem with valid attributes context. I have the following test:

 describe "POST #create" do 

    context "with valid attributes" do 
      it "saves the new car_configuration in the database" do
        expect{
          post :create, car_configuration: attributes_for(:car_configuration)
        }.to change(CarConfiguration, :count).by(1)
      end

      it "redirects to the index car_configuration" do 
        post :create, car_configuration: attributes_for(:car_configuration)
        should redirect_to admin_car_configurations_url
      end
    end
 end

And my car_configuration factory is:

FactoryGirl.define do
  factory :car_configuration do
    sequence(:image) {|n| "Image #{n}"}
    small_cases_count 5
    big_cases_count 2
    association :body_style, factory: :car_body_style
    association :model, factory: :car_model
    association :car_class
  end
end

And errors that rspec shows:

1) Admin::CarConfigurationsController POST #create with valid attributes saves the new car_configuration in the database
     Failure/Error: expect{
       count should have been changed by 1, but was changed by 0
     # ./spec/controllers/admin/car_configurations_controller_spec.rb:42:in `block (4 levels) in <top (required)>'

  2) Admin::CarConfigurationsController POST #create with valid attributes redirects to the index car_configuration
     Failure/Error: should redirect_to admin_car_configurations_url
       Expected response to be a <redirect>, but was <200>
     # ./spec/controllers/admin/car_configurations_controller_spec.rb:49:in `block (4 levels) in <top (required)>'
Was it helpful?

Solution

spec/controllers/admin/car_configuratoins_controller_spec.rb

require 'spec_helper'

describe Admin::CarConfigurationsController do
  let(:configuration) { build :configuration }

  context "POST create" do
    it "creates a config" do
      expect { perform }.to change(CarConfiguration, :count).by(1)
    end

    def perform
      post :create, car_configuration: configuration.attributes
    end
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top