用戶可依書名搜尋商品,顯示符合結果列表。
ruby script/generate controller Search search
產生 app/controllers/search_controller.rb、test/functional/search_controller_test.rb、app/views/search/search.rhtml。
在 test/functional/search_controller_test.rb:
def test_search
get :search, :title => "Pragmatic Version Control"
assert_response :success
assert_equal "Found 1 product(s).", flash[:notice]
assert_template "search/results"
products = assigns(:products)
assert_not_nil products
assert_equal 1, products.size
assert_equal "Pragmatic Version Control", products[0].title
# 驗證視圖結構:外層 div.results 內含一個 div.catalogentry
assert_tag :tag => "div", :attributes => { :class => "results" },
:children => { :count => 1, :only => { :tag => "div", :attributes => { :class => "catalogentry" } } }
end
執行測試 → 失敗(紅)。
class SearchController < ApplicationController
def search
@products = Product.find(:all, :conditions => ['title = ?', params[:title]])
if @products.any?
flash[:notice] = sprintf('Found %d product(s).', @products.size)
end
render :action => 'results'
end
def results; end # 空動作,對應 results.rhtml
end
app/views/search/results.rhtml:
<h1>Search Results</h1>
<div class="results">
<div class="catalogentry">
<%= render :partial => 'product', :collection => @products %>
</div>
</div>
app/views/search/_product.rhtml (部分模板):
<div class="product">
<h3><%= h(product.title) %></h3>
<p><%= h(product.description) %></p>
<p>Price: <%= fmt_dollars(product.price) %></p>
</div>
app/views/search/search.rhtml:
<%= form_tag :action => 'search' %>
<p>Book title: <%= text_field_tag 'title' %></p>
<p><%= submit_tag 'SEARCH' %></p>
<%= end_form_tag %>
ruby test/functional/search_controller_test.rb
# Finished in 0.094 seconds.
# 1 tests, 7 assertions, 0 failures, 0 errors
Product.search(title) 類別方法will_paginate)