micro-blogger/test/controllers/v1/blogs_controller_test.rb
2018-11-11 18:38:16 -06:00

98 lines
2.5 KiB
Ruby

# frozen_string_literal: true
require 'test_helper'
class BlogsControllerTest < ActionDispatch::IntegrationTest
test "anyone can index published blogs" do
blogs = Blog.published
get v1_blogs_url
body = JSON.parse response.body
assert_response :ok
assert_equal blogs.count, body.count
end
test "admins can index ALL blogs" do
get v1_blogs_url, headers: auth_headers(users(:admin))
body = JSON.parse response.body
assert_response :ok
assert_equal Blog.count, body.count
end
test "author can index ALL his blogs plus published" do
author = users(:author)
blogs = Blog.published.or(author.blogs)
get v1_blogs_url, headers: auth_headers(author)
body = JSON.parse response.body
assert_response :ok
assert_equal blogs.count, body.count
end
test "sally can not index authors unpublished blogs" do
bad_blog = blogs(:author2)
sally = users(:sally)
get v1_blogs_url, headers: auth_headers(sally)
body = JSON.parse response.body
blog_ids = body.each_with_object([]) { |blog, memo| memo << blog["id"] }
assert_response :ok
assert_not blog_ids.include?(bad_blog)
end
test "guests can view a published blog" do
blog = blogs(:author1)
get v1_blog_url(blog)
assert_response :success
assert_match blog.title, response.body
end
test "guests CANNOT view an unpublished blog" do
get v1_blog_url(blogs(:author2))
assert_response :unauthorized
end
test "authors can create and recieve a new blog" do
assert_difference('Blog.count') do
post v1_blogs_url, params: { blog: {
title: "This is my blog",
article: "I don't have much to say"
} }, headers: auth_headers(users(:michelle))
end
assert_response :created
assert_match(/this is my blog/i, response.body)
assert_match(/michelle/i, response.body)
end
test "author can update blog" do
patch v1_blog_url(blogs(:author1)), params: { blog: {
title: "a new title"
} }, headers: auth_headers(users(:author))
assert_response :ok
assert_match(/a new title/i, response.body)
end
test "admin can destroy a blog" do
assert_difference('Blog.count', -1) do
delete v1_blog_url(blogs(:author1)), headers: auth_headers(users(:admin))
end
assert_response :no_content
end
test "sally can destroy her blogs" do
assert_difference('Blog.count', -1) do
delete v1_blog_url(blogs(:sally1)), headers: auth_headers(users(:sally))
end
assert_response :no_content
end
end