回上一頁

RSpec寫測試之路(持續更新)

寫單元測試是後端工程師必學與必經之路的習慣,也是讓程式更穩的開發過程。

 

使用的RSpec的Gem為:https://github.com/rspec/rspec-rails

 

以下是一些常見的 RSpec 語句及寫法:

  • describe:用於描述測試的對象。
  • it:用於描述一個測試用例。
  • should:用於指定測試用例的預期結果。
  • expect:用於指定測試用例的預期結果。
  • be_:用於指定預期結果的類型。
  • eq:用於指定預期結果的相等性。
  • gt:用於指定預期結果的大於性。
  • lt:用於指定預期結果的小於性。
  • within:用於指定預期結果的範圍。
  • have:用於指定預期結果的存在性。
  • raise_error:用於指定預期結果的錯誤。

 

以下是 對 User測試的一個範例:

  
describe User do
  it { should have_many(:posts) }
  it { should validate_presence_of(:name) }
  it { should validate_uniqueness_of(:email) }

  it "should create a user with valid attributes" do
    user = User.create(name: "John Doe", email: "[email protected]")
    expect(user).to be_valid
  end

  it "should not create a user with invalid attributes" do
    user = User.create(name: "", email: "")
    expect(user).not_to be_valid
  end
end
  

 

針對基礎Controller的Iindex寫的RSpec:

  
     describe "GET #index" do
       it "assigns all model_names to @model_names" do
	    get :index
	    expect(assigns(:model_name)).to eq(@model_names)
       end
 end