Created
December 27, 2017 17:27
-
-
Save ilnurnasyrov2/b87146a6b47d4bc2681d4d51445f557e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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