środa, 24 sierpnia 2016

Extract method refactor and passing &block

Today I've tried to refactor code by extracting some part to a method. Spuriously it didn't work.

############################# first version
def generate
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000) do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
############################ second version not working
def generate
prefetch_volunteers do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
private
def prefetch_volunteers
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000)
end
view raw report.rb hosted with ❤ by GitHub
Problem was with passing block to a method. when you do that you pass block to method not the results.
In order to fix it we need to pass a block to find_each method by using &Proc.new as an extra argument. According to this article it is a fastest method.

def generate
prefetch_volunteers do |volunteer|
csv << VolunteerPresenter.new(volunteer).to_csv
end
end
private
def prefetch_volunteers
@volunteers.includes(
[:user, { taggings: :tag }]
).find_each(batch_size: 1000, &Proc.new)
end
view raw report.rb hosted with ❤ by GitHub

środa, 24 lutego 2016

Take screenshot in IntegrationTest with capybara when it fails

This is about saving screenshot on failing tests in capybara. There are bunch of advices how to do this in rspec but none for ActionDispatch::IntegrationTest. There is also a gem for this capybara-screenshot but I haven't got luck with this at all.

Here is how to do this with rails 4 integration test. Under the hood it uses minitest that have bunch of hooks we can use.

# test/test_helper.rb
class ActionDispatch::IntegrationTest
def after_teardown
if !passed?
timestamp = "#{Time.zone.now.strftime('%Y-%m-%d-%H:%M:%S')}"
screenshot_name = "screenshot-#{timestamp}.png"
# Handle CircleCi too
screenshot_path = "#{ENV.fetch('CIRCLE_ARTIFACTS', Rails.root.join('tmp/capybara'))}/#{screenshot_name}"
page.save_screenshot(screenshot_path)
end
super
end
end
view raw test_helper.rb hosted with ❤ by GitHub

Most of code stolen from http://vumanhcuongit.github.io/testing/2016/01/26/take-screenshot-when-cucumber-test-failed/ and https://github.com/mattheworiordan/capybara-screenshot