Skip to content

Instantly share code, notes, and snippets.

@artofhuman
Forked from ilnurnasyrov2/context_example.rb
Created January 24, 2018 10:26
Show Gist options
  • Save artofhuman/71faf8c803b18a745cc344c62fc1d3bb to your computer and use it in GitHub Desktop.
Save artofhuman/71faf8c803b18a745cc344c62fc1d3bb to your computer and use it in GitHub Desktop.
require 'spec_helper'
require 'ostruct'
class FakePostRepo
attr_reader :posts
def initialize
@posts = []
end
def save(post)
posts << post.merge(id: posts.count + 1)
posts.count
end
end
module ContextImport
def self.[](*dependencies)
Module.new do
attr_reader :context
def initialize(context: {}, **opts)
@context = context
super
end
dependencies.each do |dependency|
define_method(dependency) do
context.fetch(dependency)
end
end
end
end
end
Container = Dry::Container.new
Container.register :post_repo, FakePostRepo.new
Import = Dry::AutoInject(Container)
class CreatePost
include Dry::Transaction
include ContextImport[:current_user]
include Import[:post_repo]
step :save_post
def save_post(attrs)
id = post_repo.save(attrs.merge(user_id: current_user.id))
Right(id)
end
end
RSpec.describe CreatePost do
it 'saves post' do
use_case = CreatePost.new(context: { current_user: double(:user, id: 3) })
post_id = use_case.call(title: 'Some Post').value
expect(post_id).to eq 1
expect(Container[:post_repo].posts).to eq([id: 1, user_id: 3, title: 'Some Post'])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment