ruby-on-railsstubfakertest-data

How to make a shorthand for Faker typing in Rails?


Over the years, I've shied from using factory_girl and faker because I get sick of typing it all out. Is there some way of using module, classes, or aliases to get something quicker and easier to type? Thank you.


Solution

  • In your test/test_helper.rb or spec/rails_helper.rb (might be different, depending on your test suite) you can define helper functions, which can be used by all your tests, that wrap the particular FactoryBot or Faker calls you want to use. You can create shorthanded name methods like this:

    # Methods defined test/test_helper.rb or bottom of spec/rails_helper.rb
    # You can name the methods whatever you like
    
    # This returns the result of the Faker call
    def first_name
      Faker::Name.first_name
    end
    
    # Or make the method names super short if you desire
    def ln
      Faker::Name.last_name
    end
    
    # This returns a new (but not persisted) user object
    def user_new
      FactoryBot.build(:user)
    end
    
    # Should return created user
    def user_persisted
      FactoryBot.create(:user)
    end
    
    
    

    Then in your test, you can just call the function as is. You don't have to reference a class or module to call them.

    The naming convention is up to you. To prevent confusion between the helper methods' names and model attributes, I'd probably preface the helper methods with faker_ or factory_, but that's up to you.