Skip to content

Instantly share code, notes, and snippets.

@elentok
Created September 23, 2012 09:28
Show Gist options
  • Save elentok/3769483 to your computer and use it in GitHub Desktop.
Save elentok/3769483 to your computer and use it in GitHub Desktop.
testing/refactoring question (now with active_model_serializers)
class ArticleController
def comments
comments = Comment.includes(:user).find_all_by_article_id(params[:id])
render json: comments, root: false
end
end
class CommentSerializer < ActiveModel::Serializer
attributes :id, :created_at, :body, :subject
class CommentUserSerializer < ActiveModel::Serializer
attributes :id, :full_name, :avatar_url
end
has_one :user, serializer: CommentUserSerializer
end
# tests the url /articles/:id/comments
describe "GET comments" do
it "renders the json of the comments for this article" do
article = Fabricate(:article)
comment1 = Fabricate(:comment, article: article)
comment2 = Fabricate(:comment)
get :comments, {:id => article.to_param}, valid_session
# UGLYYYYYYY!!!!
expected_json = "[" + CommentSerializer.new(comment1).to_json(:root => false) + "]"
response.body.should == expected_json
end
end
@itayadler
Copy link

RSpec::Matchers.define :render_json_with do |key, value|
  match do |response|
    parsed_body = JSON.parse(response.body)
    parsed_body[key].should == value
  end
end

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