Skip to content

Instantly share code, notes, and snippets.

@joakimk joakimk/00_blog.md
Created Jul 15, 2014

Embed
What would you like to do?

I just read http://re-factor.com/blog/2013/09/27/slow-tests-are-the-symptom-not-the-cause/.

I fully agree that the testing speed can often be a result of improving the code design.

This is probably how I'd implement a similar feature in barsoom.se's apps.

I'm mostly of the opinion that you should use the right tool for each job. Integrated tests to test integration. Unit tests to test logic and message passing.

I prefer to keep things simple and avoid dependency injection until there is a need for it outside of tests.

require "attr_extras" # gem
class Controller
def add_user
user = User.finy_by_username!(params[:username])
mailing_list = MailingList.new("blog_list")
AddUserToMailingList.run(user, mailing_list)
end
end
class AddUserToMailingList
method_object :run,
:user, :mailing_list
def run
mailing_list.add_user(user)
Notify.user_added_to_mailing_list(user, mailing_list)
end
end
class MailingList
pattr_initialize :name
def add_user(user)
# Even if User owns the mailing_list_name column it doesn't need to know about it.
# Having a column like it in a central table like users would likely just be a
# simplification or an optimization in our apps.
user.update_attributes!(mailing_list_name: name)
end
end
require "spec_helper"
# non-rails unit test, much simpler than the blog example imho.
describe AddUserToMailingList, ".run" do
it "adds a user to a mailing list and notifies the user" do
user = double(:user)
mailing_list = double(:mailing_list)
expect(mailing_list).to receive(:add_user).with(user)
expect(Notify).to receive(:user_added_to_mailing_list).with(user, mailing_list)
AddUserToMailingList.run(user, mailing_list)
end
end
require "spec_helper"
describe "Adding users to mailing lists" do
it "works" do
user = create(:user)
visit user_path(user)
click_button "Add to blog list"
expect(page).to have_flash("User added to blog list")
expect(user.reload.mailing_list_name).to eq "blog_list"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.