LoginSignup
12
10

More than 5 years have passed since last update.

リダイレクトを伴うRackアプリケーションの受け入れテストと単体テストの書き方

Posted at

ちょっとややこしいタイトルだけど、つまり

  • 単体テスト (機能テスト): 正しくリダイレクトされるか
    • 正しいステータスコードか (Temporary? Permanent? See Other?)
    • 正しいリダイレクト先か
  • 受け入れテスト: リダイレクトを透過して正しい動作をしているか
    • GET /posts/1/edit -> PUT /posts/1 -> GET /posts/1 みたいなリダイレクトが透過的に行われることがある
    • GET editで入力された値がPUTで更新されたか?

RSpecの Kernel.#describe でテスト対象、つまり単体機能か操作フローか、を切り分ける。

follow_redirect! を明示的に呼ぶことでリダイレクトを追うことができるので、それの有無によってテスト対象を切り替えることができる。

describe "PostController" do
  subject { last_response }

  before do
    __send__(http_method, request_url)
  end

  let(:http_method) { :get }

  describe 'PUT', '/posts/:id' do
    let(:mock_post) { Fabricate(:post) }
    let(:http_method) { :put }
    let(:request_url) { app.url(:posts, :show, :id => mock_post.id) } # -> /posts/1

    describe "redirection" do
      it { should be_redirect }
      its(['Location']) { should eq request_url } # -> should eq "/posts/1"
    end

    describe "callback" do
      before do
        follow_redirect!
      end

      it { should be_ok }
    end
  end
end
12
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
10