在控制器规格中发布请求

时间:2014-03-11 14:18:18

标签: ruby-on-rails rspec ruby-on-rails-4 rspec-rails

我测试控制器时遇到问题。我在2个上下文中测试了帖子请求。使用有效属性和无效属性。我有效的属性上下文有问题。 我有以下测试:

 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

我的car_configuration工厂是:

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

rspec显示的错误:

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)>'

1 个答案:

答案 0 :(得分:0)

规格/控制器/管理/ 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