使用 context 整理重複語句

有沒有覺得 when course doesn't have a titlewhen course has title 要一直重複打看得很煩呢?

describe "POST create" do
  it "doesn't create a record when course doesn't have a title" do
    expect do
      post :create, params: { course: { :description => "bar" }}
    end.to change { Course.count }.by(0)
  end

  it "render new template when course doesn't have title" do
    post :create, params: { course: { :description => "bar" } }

    expect(response).to render_template("new")
  end

  it "create a new course record when course has title" do
    course = build(:course)

    expect do
      post :create, params: { course: attributes_for(:course) }
    end.to change { Course.count }.by(1)
  end

  it "redirects to courses_path when course has title" do
    course = build(:course)

    post :create, params:{ course: attributes_for(:course) }

    expect(response).to redirect_to courses_path
  end
end

事實上,RSpec 提供一個簡化用的 syntax:context,你可以使用 context 把重複的場景包成一個 block,如重新整理成

describe "POST create" do
  context "when course doesn't have a title " do
    it "doesn't create a record" do
      expect{ post :create, course: {:description => "bar"} }.to change{Course.count}.by(0)
    end

    it "render new template" do
      post :create, course: {:description => "bar"}

      expect(response).to render_template("new")
    end
  end

  context "when course have a title " do
    it "create a new course record" do
      course = FactoryGirl.build(:course)

      expect{ post :create, course: FactoryGirl.attributes_for(:course)}.to change{ Course.count}.by(1)
    end

    it "redirect to courses_path" do
      course = FactoryGirl.build(:course)

      post :create, course: FactoryGirl.attributes_for(:course)

      expect(response).to redirect_to courses_path
    end
  end
end

這樣看起來就清爽許多了,可讀性也大大提高。

使用 --format documentation 選項執行測試時也有較清晰的測試輸出:

$ rspec --format documentation spec/controllers/courses_controller_spec.rb

CoursesController
  GET index
    assigns @courses and render
    render template
  GET show
    assigns @course
    render template
  GET new
    assign @course
    render template
  POST create
    when course doesn't have title
      doesn't create a record
      render new template
    when course has title
      create a new course record
      redirects to courses_path

results matching ""

    No results matching ""