Skip to content

Instantly share code, notes, and snippets.

@daniloisr
Created July 30, 2015 13:07
Show Gist options
  • Save daniloisr/097d9debe294e20e8cbd to your computer and use it in GitHub Desktop.
Save daniloisr/097d9debe294e20e8cbd to your computer and use it in GitHub Desktop.
unless File.exist?('Gemfile')
File.write('Gemfile', <<-GEMFILE)
source 'https://rubygems.org'
ruby '2.1.5'
gem 'rails' , '4.2.0'
gem 'arel'
gem 'sqlite3'
gem 'active_model_serializers', '0.9.2'
gem 'pry'
GEMFILE
system 'bundle'
end
require 'bundler'
Bundler.setup(:default)
require 'active_record'
require 'active_model_serializers'
require 'minitest/autorun'
require 'logger'
# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.string :title
t.text :body
end
create_table :comments, force: true do |t|
t.integer :post_id
t.string :name
t.text :body
end
end
class Post < ActiveRecord::Base
validates :title, :body, presence: true
has_many :comments
end
class Comment < ActiveRecord::Base
validates :name, :body, :post_id, presence: true
belongs_to :post
end
ActiveModel::Serializer.setup do |config|
config.embed = :ids
config.embed_in_root = true
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body
has_many :comments#, embeds: :ids, embed_in_root: true
end
class CommentSerializer < ActiveModel::Serializer
attributes :id, :name, :body
end
class BugTest < Minitest::Test
def test_filter_method
post = Post.create!(title: 'Test filter', body: 'Test if the filter method is working fine')
comment_1 = Comment.create!(name: 'Prasad', body: 'checking...', post: post)
comment_2 = Comment.create!(name: 'Prasad', body: 'checked. works fine.', post: post)
assert_equal CommentSerializer.new(comment_1).to_json, {comment: {id: comment_1.id, name: comment_1.name, body: comment_1.body}}.to_json
assert_equal PostSerializer.new(post).to_json, {post: {id: post.id, title: post.title, body: post.body, comment_ids: [comment_1.id, comment_2.id]}, comments: [{id: comment_1.id, name: comment_1.name, body: comment_1.body}, {id: comment_2.id, name: comment_2.name, body: comment_2.body}]}.to_json
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment