Quần Cam

Using Factory Girl with Hanami model

Hanami is one of the most popular and trending Ruby frameworks today, well-known for its clean architecture and testability. In this post we are going to explore how we can use Hanami Model with Factory for fast testing data generation.

Data Persistence in Hanami

Model is one of the best features of Hanami, with the separation of Entity and Repository, following the architecture of Domain Driven Design. Entity holds the domain logic, whilst Repository is responsible for persistence.

Here is the code example to persist data with Hanami Model.

class Book
  include Hanami::Entity
  attribute :title, :author
end

class BookRepository
  include Hanami::Repository
end

# And to persist
book = Book.new(title: 'Ruby Under a Microscope', author: 'Pat Shaughnessy'))
BookRepository.create(book)

Using Factory Girl for test data production

Factory Girl has been widely adopted for testing data production by the Ruby on Rails community, but it could be used in PORO way. So let’s see how we can integrate Factory Girl in our Hanami application for testing.

Generally here is how you generate data with Factory Girl in RSpec.

FactoryGirl.define do
  factory :book do
    title 'The sample book'
    author 'John Cena'
  end
end

describe Book do
  it 'does something' do
    book = create(:book)
  end
end

By default, Factory Girl will call the #save! method of the instance. But in Hanami we use Repository to persist data, as mentioned above.

But Factory Girl already got you covered.

FactoryGirl.define do
  factory :book do
    title 'The sample book'
    author 'John Cena'

    # Add your custom method here to persist object
    to_create { |instance| BookRepository.create(instance) }
  end
end

That’s it! Enjoy coding!


NGUY HIỂM! KHU VỰC NHIỀU GIÓ!
Khuyến cáo giữ chặt bàn phím và lướt thật nhanh khi đi qua khu vực này.
Chức năng này hỗ trợ markdown và các thứ liên quan.

Bài viết cùng chủ đề

Euruko 2017 Notes

Vừa rồi mình đi Euruko 2017 ở Budapest, một số bài nói cũng khá thú vị nên mình sẽ note lại ở đây.

Six confusing features in Ruby

In this post I am trying to point out some Ruby features you might want to use with a lot of caution.

Bundler Gotcha

A few days ago I encountered a strange behavior of Bundler so this post notes down how my experience with it was.