Created
September 23, 2014 17:57
-
-
Save thehenster/546d3d3104e88b4c925e to your computer and use it in GitHub Desktop.
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
source 'https://rubygems.org' | |
gem 'pg' | |
gem 'activerecord' |
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 'bundler/setup' | |
require 'pg' | |
require 'active_record' | |
require 'minitest/autorun' | |
ActiveRecord::Base.establish_connection( | |
adapter: 'postgresql', | |
host: 'localhost', | |
username: 'postgres', | |
password: '', | |
database: 'testy_test' | |
) | |
describe 'json typecasting' do | |
class Post < ActiveRecord::Base | |
validate :data_is_valid_json | |
def data=(str) | |
begin | |
super(str) | |
rescue JSON::ParserError | |
@__original_data_json_string = str | |
end | |
end | |
private | |
def data_is_valid_json | |
return unless @__original_data_json_string | |
begin | |
JSON.parse(@__original_data_json_string) | |
rescue JSON::ParserError | |
errors.add :data, 'invalid JSON' | |
end | |
end | |
end | |
before do | |
ActiveRecord::Base.connection.create_table :posts do |t| | |
t.json :data | |
end | |
end | |
after do | |
ActiveRecord::Base.connection.drop_table :posts | |
end | |
it 'persists using real json' do | |
p = Post.create data: "{\"foo\" : \"bar\"}" | |
assert p.persisted? | |
assert_equal({'foo' => 'bar'}, p.data) | |
end | |
it 'adds an error when using invalid json' do | |
p = Post.create data: "invalid json" | |
assert p.errors.any? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment