【发布时间】:2017-07-13 08:10:36
【问题描述】:
我尝试使用 rspec 为我的 rails 应用程序运行更新测试。
我正在使用 rspec 3.5 和 rails 4。
行为应该如下:
当我创建一个具有售价的新服务时,它会创建一个 Price 实例并设置与服务的关系。然后,当我更新我的服务时,如果没有售价,它会破坏价格记录(客户要求节省数据库空间)。 我实现的过程似乎运行良好,当我使用 UI 进行测试并检查价格记录的计数时,它就像假设的那样减少了一个。但是,如果失败,则进行单元测试。
代码如下:
服务控制器:
def update
@service.assign_attributes(service_params)
puts "update method"
respond_to do |format|
if @service.valid?
if params['preview']
@service.build_previews
format.js { render 'services/preview' }
else
@service.save!
format.html { redirect_to client_trip_days_path(@client, @trip), notice: t('flash.services.update.notice') }
end
else
format.html { render :edit }
format.js { render :new }
end
end
end
Service 模型中的回调:
def create_or_update_price
puts "in create or update price"
if selling_price.present? && price.present?
self.price.update_columns(:trip_id => trip.id, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif selling_price.present? && !price.present?
self.price = RegularPrice.create(:trip => trip, :currency => trip.client.currency, :purchase_price => purchase_price, :selling_price => selling_price)
elsif !selling_price.present? && price.present?
self.price.destroy
end
end
测试:
it "updates the lodging and destroy the price" do
puts "nombre de service avant création : "
puts Service.count
puts "nombre de prix avant création : "
puts Price.count
lodging = FactoryGirl.create(:lodging_service, selling_price: 200)
puts "nombre de service après création : "
puts Service.count
puts "nombre de prix après création : "
puts Price.count
expect(lodging.reload.price).to be_present
puts "nombre de prix avant update : "
puts Price.count
puts "id"
puts lodging.id
patch :update, client_id: client.id, trip_id: trip.id, id: lodging.to_param, service: valid_attributes_no_more_price
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_with_price
puts "nombre de prix après update : "
puts Price.count
# expect{
# patch :update, client_id: client.id, trip_id: trip.id, id: lodging.id, service: valid_attributes_no_more_price
# }.to change(RegularPrice, :count).by(0)
expect(lodging.reload.price).to be_nil
end
let(:valid_attributes_no_more_price) {
attributes_for(:lodging_service, trip: trip, selling_price: "")
}
如您所见,由于我试图找出问题所在,因此出现了很多 put。
输出是: 服务前卫的名称: 0 nombre de prix avant création : 0 在创建或更新价格 服务后创建的名称: 1 名称 après création : 1 nombre de prix avant 更新: 1 ID 10 nombre de prix après 更新: 1
失败/错误:expect(lodging.reload.price).to be_nil
expected: nil
got: #<RegularPrice id: 2, label: nil, currency: "CHF", selling_price: 200.0, priceable_type: "Service", p...ated_at: "2017-07-13 08:08:47", quantity: 1, type: "RegularPrice", position: 1, purchase_price: nil>
如我们所见,更新后似乎没有触发回调,也没有到达控制器中的操作。
你知道出了什么问题吗?
谢谢:)
PS:我的问题中总是无法包含代码,是否有关于如何制作它的教程?
【问题讨论】:
-
对于本教程,当您提出或回答问题时,会有一个“?”编辑器右上角(在工具栏上)的图标,如果单击它,您可以查看一些快速帮助和“高级帮助”链接,您是否浏览并阅读了这些?
-
您的问题解决了吗?
标签: ruby-on-rails rspec factory-bot