测试驱动开发:如何在测试之上不重复自己?

时间:2011-06-26 17:04:27

标签: ruby-on-rails-3 rspec

我将此文件作为我的起点

require 'spec_helper'

describe PagesController do
  render_views  
  describe "GET 'home'" do
    it "should be successful" do
      @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
      get 'home'
      response.should be_success
    end

    it "Should have the proper title" do
      @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
      get 'home'
      response.should have_selector( "title",
      :content => "Slacklog")
    end
  end

  describe "GET 'contact'" do
    it "should be successful" do
      @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
      get 'contact'
      response.should be_success
    end
  end

  describe "GET 'about'" do
    it "should be successful" do
      @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
      get 'about'
      response.should be_success
    end
  end

end

但你注意到了这一行

      @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")

这是我的基本HTTP身份验证,我在所有测试中都需要这个,但我需要更好的方法是在我的所有测试之前添加这个,然后在所有测试之上复制和粘贴

1 个答案:

答案 0 :(得分:1)

describe PagesController do

  before(:each) do
    @request.env["HTTP_AUTHORIZATION"] = "Basic " + Base64::encode64("username:password")
  end

  ...

end