require "test_helper"

class Admin::PostsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @post = posts(:one)

    post login_path, params: {user: {
      email: users(:user_one).email,
      password: "12345678"
    }}
  end

  test "should get index" do
    get admin_posts_path
    assert_response :success
  end

  test "should get new" do
    get new_admin_post_path
    assert_response :success
  end

  test "should saved a draft post" do
    assert_difference("Post.count") do
      category1 = post_categories(:cat_one)
      post admin_posts_path, params: {post: {content: "Post content 000", title: "This is a post 000", post_category_id: category1.id}}
    end

    post = Post.where(title: "This is a post 000").first
    assert_equal true, post.is_draft?
    assert_equal true, post.published_at.blank?
    assert_redirected_to edit_admin_post_path(Post.last)
  end

  test "should published a new post" do
    assert_difference("Post.count") do
      category1 = post_categories(:cat_one)
      post admin_posts_path, params: {publish: "Publish", post: {content: "Post content 001", title: "This is a post 001", post_category_id: category1.id}}
    end

    post = Post.where(title: "This is a post 001").first
    assert_equal true, post.published?
    assert_equal true, post.published_at.present?
    assert_redirected_to edit_admin_post_path(Post.last)
  end

  test "should show post" do
    get admin_post_path(@post)
    assert_response :success
  end

  test "should get edit" do
    get edit_admin_post_path(@post)
    assert_response :success
  end

  test "should update a draft post" do
    category1 = post_categories(:cat_one)
    patch admin_post_path(@post), params: {post: {content: @post.content, title: @post.title, post_category_id: category1.id}}
    assert_equal true, @post.is_draft?
    assert_redirected_to edit_admin_post_path(@post)
  end

  test "should published a draft post" do
    category1 = post_categories(:cat_one)
    patch admin_post_path(@post), params: {publish: "Publish", post: {content: @post.content, title: @post.title, post_category_id: category1.id}}
    @post.reload
    assert_equal true, @post.published?
    assert_equal true, @post.published_at.present?
    assert_redirected_to edit_admin_post_path(@post)
  end

  test "should destroy post" do
    assert_difference("Post.count", -1) do
      delete admin_post_path(@post)
    end

    assert_redirected_to admin_posts_path
  end
end
