如何测试在Rspec功能规范中使用父记录的回调

问题描述 投票:0回答:1

我具有创建order的功能规格。 order具有如下回调:

class Order
  belongs_to :site
  before_validation :add_call_number

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

在规范中,call_number_start出现NoMethod错误,因为self.site不存在。

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

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

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

我以为这是数据库清理程序的问题,所以我非常认真地去手动将其设置为truncation方法,如下所示:

# 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

如何正确测试此回调?

ruby-on-rails rspec
1个回答
0
投票

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

该站点是否来自Controller中的order_params?然后在控制器中找出为什么站点不可用。

该网站与订单相关吗?然后需要创建订购站点:

FactoryBot.create(:site, order: order)
© www.soinside.com 2019 - 2024. All rights reserved.