Exercises

重構 Home page,把 if-else 述句的兩個分支分別放到單獨的 partial 中


為側邊欄的 micropost 數量編寫測試(還要檢查使用正確的複數形),可以參考以下程式碼:

test/integration/microposts_interface_test.rb

require 'test_helper'

class MicropostInterfaceTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end
  .
  .
  .
  test "micropost sidebar count" do
    log_in_as(@user)
    get root_path
    assert_match "#{FILL_IN} microposts", response.body
    # User with zero microposts
    other_user = users(:malory)
    log_in_as(other_user)
    get root_path
    assert_match "0 microposts", response.body
    other_user.microposts.create!(content: "A micropost")
    get root_path
    assert_match FILL_IN, response.body
  end
end

以下列程式碼為範例,為 Section 11.4 的圖片上傳程序編寫測試:

test/integration/microposts_interface_test.rb

require 'test_helper'

class MicropostInterfaceTest < ActionDispatch::IntegrationTest

  def setup
    @user = users(:michael)
  end

  test "micropost interface" do
    log_in_as(@user)
    get root_path
    assert_select 'div.pagination'
    assert_select 'input[type=FILL_IN]'
    # Invalid submission
    post microposts_path, micropost: { content: "" }
    assert_select 'div#error_explanation'
    # Valid submission
    content = "This micropost really ties the room together"
    picture = fixture_file_upload('test/fixtures/rails.png', 'image/png')
    assert_difference 'Micropost.count', 1 do
      post microposts_path, micropost: { content: content, picture: FILL_IN }
    end
    assert FILL_IN.picture?
    follow_redirect!
    assert_match content, response.body
    # Delete a post.
    assert_select 'a', 'delete'
    first_micropost = @user.microposts.paginate(page: 1).first
    assert_difference 'Micropost.count', -1 do
      delete micropost_path(first_micropost)
    end
    # Visit a different user.
    get user_path(users(:archer))
    assert_select 'a', { text: 'delete', count: 0 }
  end
  .
  .
  .
end

測試之前,要在 fixtures 目錄底下放一張圖片(例如,可以執行 cp app/assets/images/rails.png test/fixtures/ 指令)。

為避免出現難以理解的錯誤,要先設定 CarrierWave,在測試中不調整圖片尺寸,方法是建立一個初始化的檔案,如以下程式碼內容:

config/initializers/skip_image_resizing.rb

if Rails.env.test?
  CarrierWave.configure do |config|
    config.enable_processing = false
  end
end

上述的測試中,加了幾個 assertions,檢查 Home page 有沒有檔案上傳欄位,以及成功提交表單後有沒有正確設定 picture 屬性的值。

注意,在測試中上傳 fixtures 的檔案使用的是專門的 fixture_file_upload 方法。

如果使用 Windows 系統,要加上 :binary 參數:fixture_file_upload(file, type, :binary)

提示,為了檢查 picture 屬性值,可以使用 Section 10.1.4 介紹的 assigns 方法,在提交成功後取得 create action 中的 @micropost 變數。