Monthly Archives: November 2018

In FactoryBot, you can reference fields of a factory when defining other fields of the same factory. That helps reduce code duplication!

For example, suppose you have a Person class that has the fields first_name and full_name. You can define the Person factory so that full_name will reference first_name.

That looks like this:

factory :person do
  sequence(:first_name) { |n| "foo#{n}"}
  full_name { first_name.capitalize + " Smith" }

This was tricky to figure out, so I’m jotting it down here!

When you’re running a simple Flask app in development, you might specify a particular port where the server should run (the default is 5000).

Then in your browser you can visit localhost:5000/foobar.

But in Flask tests you don’t need to specify the port, just the route:

from flask_testing import TestCase

class TestFoobar(TestCase):
    def test_foobar(self):
        response = self.client.get("/foobar")
        # ...

That’s because, underneath, Werkzeug test clients don’t issue actual HTTP requests. They abstract that away.

Source: this Stack Overflow post.

Sometimes you just need long strings.

In tests, I sometimes like to include tiny CSVs as a part of the test code instead of a fixture file. However, that looks real gross real fast with all the linebreaks.

Heredocs to the rescue!

In Ruby, instead of:

sample_csv = "foo,bar,baz\na,b,c\nd,e,f\n,g,h,i"

You can do something like:

sample_csv = <<~EOS

Isn't that much better?

Suppose you want an endpoint that returns a file that the browser would open a “file download” dialogue. You can do so by setting the Content-Disposition.


class FooController < ApplicationController
  def show
    response.headers["Content-Disposition"] = "attachment; filename=foo.txt"
    render plain: "foobar"

In the example, when hitting the show path, most browsers will pop open a download box asking to save "foo.txt". Note, that you need to pass in "Content-Disposition" (string) and not :content_disposition (symbol).