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.' }
end
assert_redirected_to post_path(assigns(:post))
assert_equal 'Post was successfully created.', flash[:notice]
end
というテストコードを書いた。最初の"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.new(params[:post]) respond_to do |format| if @post.save flash[:notice] = 'Post was successfully created.' format.html { redirect_to(@post) } format.xml { render :xml => @post, :status => :created, :location => @post } else 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の形式:
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:
Post a Comment