Skip to content

Instantly share code, notes, and snippets.

@wojtekmach
Created August 28, 2011 12:19
Show Gist options
  • Save wojtekmach/1176601 to your computer and use it in GitHub Desktop.
Save wojtekmach/1176601 to your computer and use it in GitHub Desktop.
minitest + valid_attribute
gem "minitest"
require "minitest/spec"
require "minitest/autorun"
require "active_model"
require "test/unit"
require "valid_attribute"
require "turn"
class MiniTest::Unit::TestCase
extend ValidAttribute::Method
end
class Post
attr_accessor :title
include ActiveModel::Validations
validates :title, :presence => true, :length => 2..16
end
class MiniTest::Spec
class << self
def it_must &block
matcher = yield
it "must #{matcher.description}" do
result = matcher.matches? subject
assert result, matcher.failure_message
end
end
def it_wont &block
matcher = yield
it "wont #{matcher.description}" do
result = matcher.does_not_match? subject
assert result, matcher.negative_failure_message
end
end
end
end
describe "Post" do
subject { Post.new }
it_must { have_valid(:title).when("Hello") }
it_wont { have_valid(:title).when(nil, "", "X") }
end
@bcardarella
Copy link

Can we just use must and wont?

describe "Post" do
  subject { Post.new }

  must { have_valid(:title).when('Hello') {
  wont { have_valid(:title).when(nil, '', 'X') }
end

I'm unfamiliar with Minitest so I don't know if these are reserved in any way. But to me it looks better. Or even, to stick with Minitest semantics:

describe "Post" do
  subject { Post.new }

  must_be { valid(:title).when('Hello') {
  wont_be { valid(:title).when(nil, '', 'X') }
end

This of course might be limiting as the method name valid could be fairly common.

@wojtekmach
Copy link
Author

I created a separate issue on the minitest project page minitest/minitest#33 so we'll see how it goes there.
The way i see it we have two options to continue:
a) Minitest itself will have a support for matchers (included or via a gem)
b) Something along these lines:

module ValidAttribute::MiniTest
  def must_have_valid attr ; end
  def wont_have_valid attr ; end
end

describe "Post" do
  extend ValidAttribute::MiniTest
  subject { Post.new }

  must_have_valid(:title).when("Hello")
end

That extend ValidAttribute::MiniTest can of course be pushed inside MiniTest::Spec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment