How to test callback that uses parent record in Rspec Feature spec

早过忘川 提交于 2020-03-25 18:21:01

问题


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 call_number
    self.call_number = self.site.call_number_start
  end
end

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

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

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

How can I correctly test this callback?


回答1:


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

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)


来源:https://stackoverflow.com/questions/60806143/how-to-test-callback-that-uses-parent-record-in-rspec-feature-spec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!