Igor Alexandrov

Programming and something else…

Factory Girl – Not Only for Rails Models

| Comments

We in JetRockets widely use Factory Girl as a fixture replacement for our tests. A couple of days ago I replaced Test::Unit with RSpec for our wiselinks gem. I wanted to emulate situation when controller is processing wiselinks and non-wiselinks requests. To do this I had to create instance of ActionDispatch::Request inside of my specs and Factory Girl helped me a lot with this.

Wiselinks sends special HTTP headers inside XMLHttpRequest call. With these headers you can determine that request is sent with wiselinks and you should not render full layout for it. To do this easier we extended ActionDispatch::Request with a couple of methods: * #wiselinks? * #wiselinks_template? * #wiselinks_partial?

This is what I wanted to test. I created common rspec sceleton file:

1
2
3
4
5
require "helper"

describe ActionDispatch::Request do
  # context and describe blocks
end

Then I tried several ways to create instance of ActionDispatch::Request and finally I used Factory Girl like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require 'faker'

FactoryGirl.define do
  factory :request, :class => ActionDispatch::Request do |r|
    trait :wiselinks do
      after(:build) do |obj|
        obj.env['X-Render'] = Faker::Lorem.characters(10)
      end
    end

    trait :wiselinks_template do
      after(:build) do |obj|
        obj.env['X-Render'] = 'template'
      end
    end

    trait :wiselinks_partial do
      after(:build) do |obj|
        obj.env['X-Render'] = 'partial'
      end
    end


    initialize_with{ new(Rack::MockRequest.env_for('/')) }

    factory :wiselinks_request,   traits: [:wiselinks]
    factory :wiselinks_template_request,   traits: [:wiselinks_template]
    factory :wiselinks_partial_request,   traits: [:wiselinks_partial]
  end
end

Now I can use it as FactoryGirl.build(:wiselinks_request) and it will be real instance of ActionDispatch::Request with properly initialized environment.

Easy!

Comments