Created
August 12, 2009 17:12
-
-
Save znz/166617 to your computer and use it in GitHub Desktop.
Sequelを使ったときのテストがうまく書けない
This file contains hidden or 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
memo.db |
This file contains hidden or 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 'rubygems' | |
require 'sequel' | |
Sequel::Model.plugin(:schema) | |
Sequel.connect("sqlite://memo.db") | |
class Memo < Sequel::Model | |
unless table_exists? | |
set_schema do | |
primary_key :id | |
string :memo_id, :unique => true, :null => false | |
text :body | |
end | |
create_table | |
end | |
def self.make_id | |
Time.now.to_i.to_s(36).reverse | |
end | |
def before_create | |
self.memo_id ||= make_id | |
end | |
end | |
def create_memo(body, memo_id=Memo.make_id) | |
values = { | |
:body => body, | |
:memo_id => memo_id, | |
} | |
begin | |
retry_count = 0 | |
Memo.create(values) | |
rescue Sequel::DatabaseError => e | |
if /memo_id is not unique/ =~ e.to_s && retry_count < 3 | |
values[:memo_id].succ! | |
retry | |
end | |
raise e | |
end | |
end |
This file contains hidden or 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
#!/usr/bin/ruby -Ku | |
require 'test/unit' | |
require 'memo' | |
class PasteTest < Test::Unit::TestCase | |
TEST_DB = "test.db" | |
def setup | |
@db = Sequel.connect("sqlite://#{TEST_DB}") | |
end | |
def teardown | |
@db.disconnect | |
File.unlink(TEST_DB) if File.exist?(TEST_DB) | |
end | |
def test_memo_body | |
memo = create_memo("foo", "foo") | |
assert_equal("foo", memo.body) | |
memo = create_memo("bar", "foo") | |
assert_equal("bar", memo.body) | |
end | |
def test_memo | |
memo = create_memo("foo", "foo") | |
assert_equal("foo", memo.memo_id) | |
memo = create_memo("foo", "foo") | |
assert_equal("fop", memo.memo_id) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment