Reputation: 4049
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
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?
Upvotes: 0
Views: 85
Reputation: 9949
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)
Upvotes: 0