Ruby on rails 如何在RSpec测试中为发票自动创建嵌套项?

Ruby on rails 如何在RSpec测试中为发票自动创建嵌套项?,ruby-on-rails,rspec,factory-bot,rspec-rails,Ruby On Rails,Rspec,Factory Bot,Rspec Rails,大家新年快乐 在我的Rails应用程序中,我有发票,可以有许多嵌套的项目: class Invoice < ActiveRecord::Base belongs_to :user has_many :items accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true ... end 告诉RSpec它应该始终包括2个项目以及测试期间创建

大家新年快乐

在我的Rails应用程序中,我有
发票
,可以有许多嵌套的
项目

class Invoice < ActiveRecord::Base

  belongs_to :user

  has_many :items

  accepts_nested_attributes_for :items, :reject_if => :all_blank, :allow_destroy => true

  ...

end
告诉RSpec它应该始终包括2个
项目
以及测试期间创建的任何
发票
的最佳方式是什么

我发现这很困难,因为RSpec不关心我的
控制器操作

Rails是如何做到这一点的


谢谢您的帮助。

您可以使用factory\u girl的calbacks功能。以下是一篇关于这方面的文章:

在这种情况下,添加到发票工厂的以下行可能会执行此操作:

after(:create) {|instance| create_list(:item, 2, invoice: instance) }
Rspec应该这样使用它:

class InvoicesController < ApplicationController

  before_action :find_invoice

  ...

  def new
    @invoice = current_user.invoices.build(:number => current_user.next_invoice_number)
    @invoice.build_item(current_user)
  end 

  def create
    @invoice = current_user.invoices.build(invoice_params)   
    if @invoice.save
      flash[:success] = "Invoice created."
      redirect_to edit_invoice_path(@invoice)
    else
      render :new
    end
  end

  ...

  private

  def find_invoice
    @invoice = Invoice.find(params[:id])
  end

end
describe InvoicesController do

  describe "#new" do
    before do
      create(:invoice)
    end 

    # expectations here

  end

end

将其与
瞬态
块相结合可能很有用。(对于较旧版本的factory_girl,可使用
忽略
块。)
describe InvoicesController do

  describe "#new" do
    before do
      create(:invoice)
    end 

    # expectations here

  end

end