如何在 Rspec Feature 规范中测试使用父记录的回调 [英] How to test callback that uses parent record in Rspec Feature spec

查看:42
本文介绍了如何在 Rspec Feature 规范中测试使用父记录的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能规范来创建订单.那个 order 有一个这样的回调:

I have a feature spec to create an order. That order has a callback like so:

class Order
  belongs_to :site
  before_validation :add_call_number

  def add_call_number
    self.call_number = self.site.call_number_start
  end
end

在规范中,我在 call_number_start 上收到 NoMethod 错误,因为 self.site 不存在.

In the spec, I get a NoMethod error on call_number_start, because self.site doesn't exist.

我发现在操作之前我在 Rspec 中创建的 Site 根本不存在.换句话说...

I discovered that the Site I created in the Rspec before action doesn't exist at all. In other words...

require 'rails_helper'

describe "create successfully", type: :feature, js: true do
  before do
    @site = create(:site)
    visit "/orders"
    .... # various actions to build an order using the page's form
    puts ">>>>>"
    puts "site in before action: #{Site.all.size}"
    find("#checkoutModal #submit").click()
    sleep(1)
  end
  it "should create" do
    expect(Order.all.size).to equal(1)
    expect(Order.last.call_number).to equal(@site.call_number_start)
  end
end

# controller action that #submit POSTs to
def create
  puts ">>>>>"
  puts "site in controller create: #{Site.all.size}"
  puts ">>>"
  puts "site_id from order_params: #{order_params[:site_id]}"
  @order = Order.new(order_params)
  @order.save if @order.valid?
end

def order_params
  params.require(:order).permit(:site_id)
end

# puts output:
>>>>>
site in before action: 1
>>>>>
site in controller create: 0
>>>
site_id from order_params: 1

我认为这是一个数据库清理问题,所以我非常迂腐地将其手动设置为 truncation 方法,如下所示:

I thought this was a database cleaner issue, so I went really pedantically to manually set it up as truncation method like this:

# rails_helper.rb

Rspec.configure do |config|
  config.use_transactional_fixtures = false
  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each, truncate: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

如何正确测试此回调?

推荐答案

您创建了一个站点,但没有在控制器中对其进行排序.

You created a site but did not give it to order in the controller.

该站点是否来自 Controller 中的 order_params?然后在控制器中找出站点不可用的原因.

Is the site coming from order_params in Controller? Then figure out in controller why site is not available.

网站是否与订单有关联?然后需要为订单创建站点:

Is the site an association with the order? Then need to create the site for order:

FactoryBot.create(:site, order: order)

这篇关于如何在 Rspec Feature 规范中测试使用父记录的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆