rspec预期#count已更改为1,但已更改为0

时间:2018-03-12 18:59:53

标签: ruby-on-rails factory-bot

我在locations_controller_spec.rb中有以下内容:

describe 'create' do
 it 'should create the record' do
   expect do
     post :create, params: { location: FactoryBot.attributes_for(:location) }
   end.to change(Location, :count).by(1)
 end
end

我的工厂有:

FactoryBot.define do
  factory :location do
    name              'MyString'
    hours_operation   'MyString'
    abbreviation      'MyString'
    address_1         'MyString'
    address_2         'MyString'
    city              'MyString'
    state             'MyString'
    postal_code       1
    phone             'MyString'
    fax               'MyString'
    association       :region
  end
end

我播种数据库以摆脱需要存在的区域的问题,但现在我得到了:

Admin::LocationsController create should create the record
 Failure/Error:
   expect do
     post :create, params: { location: FactoryBot.attributes_for(:location) }
   end.to change(Location, :count).by(1)

我错过了什么?地点正在存储。

编辑:以下是导致此问题的控制器:

def create
 @region = Region.find(params[:region_id])
 @location = @region.location.new(location_params)
 flash[:notice] = 'Location created successfully'if @region.location << @location
 respond_with @location, location: admin_locations_path
end

1 个答案:

答案 0 :(得分:0)

我搞砸了控制器的创建方法。一旦我把它换回来它就起作用了:

def create
 @location = Location.new(location_params)
 flash[:notice] = 'Location created successfully' if @location.save
 respond_with @location, location: admin_locations_path
end