Monday, October 05, 2009

Rails Functional Test (2)

A Guide to Testing Rails Applications


  test "should create post" do
    assert_difference('Post.count') do
      post :create, :post => { :title => 'Hi', :body => 'This is my first post.' }

    assert_redirected_to post_path(assigns(:post))
    assert_equal 'Post was successfully created.', flash[:notice] 

というテストコードを書いた。最初の"post :create, :post => { :title => 'Hi', :body => 'This is my first post.' }" はpostコントローラにcreate アクションを実行。":post" symbol にpost controllerのcreate actionに対する引数を与えた。(パラメータは{ :title => 'Hi', :body => 'This is my first post.' })
次のassert文 "assert_redirected_to post_path(assigns(:post))" 。よくわからないが,"format.html { redirect_to(@post) }" に関連したテストなのだろうか?
最後のassert文,"assert_equal 'Post was successfully created.', flash[:notice]" で,flash[:notice]に "Post was successfully created" が渡されているかどうかをテスト。post_controller.rb を見ると,flash[:notice] に "Post was successfully created" が引き渡されていた。

  def create
    @post =[:post])

    respond_to do |format|
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to(@post) }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }


4.6 Testing Views

viewのテストとして,key HTML elementsの存在やコンテンツに対するassertingをすることによって,viewのテストを行う。
"assert_select" を使うことで,simpleだけどpowerfulなsyntaxを使うことができる。

assert_select (selecter, [equality], [message]) ensures that the equality condition is met on the selected elements through the sector. The selector may be a CSS selector expresion (String), an expression with substitution valutes, or an HTML::Selector object.
assert_select (element, selecter, [equality], [message]) ensures that the equality condition is met on all the selected elements through the selector starting from the element (instance of HTML::Node) and its descendants.

  assert_select 'title', "Welcome to Rails Testing Guide"

No comments:

There was an error in this gadget