rspec 预期 #count 已更改为 1,但已更改为 0
rspec expected #count to have changed by 1, but was changed by 0
我的 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
我弄乱了控制器的创建方法。一旦我将其切换回来,它就起作用了:
def create
@location = Location.new(location_params)
flash[:notice] = 'Location created successfully' if @location.save
respond_with @location, location: admin_locations_path
end
我的 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
我弄乱了控制器的创建方法。一旦我将其切换回来,它就起作用了:
def create
@location = Location.new(location_params)
flash[:notice] = 'Location created successfully' if @location.save
respond_with @location, location: admin_locations_path
end