用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# 7.7 练习 电子书中有练习的答案,如果想阅读参考答案,请[购买电子书](http://railstutorial-china.org/#purchase)。 避免练习和正文冲突的方法参见[3.6 节](chapter3.html#mostly-static-pages-exercises)中的说明。 1. 确认[代码清单 7.31](#listing-gravatar-option) 中的代码允许 [7.1.4 节](#a-gravatar-image-and-a-sidebar)定义的 `gravatar_for` 辅助方法接受可选的 `size` 参数,可以在视图中使用类似 `gravatar_for user, size: 50` 这样的代码。([9.3.1 节](chapter9.html#users-index)会使用这个改进后的辅助方法。) 2. 编写测试检查[代码清单 7.18](#listing-f-error-messages) 中实现的错误消息。测试写得多详细由你自己决定,可以参照[代码清单 7.32](#listing-error-messages-test)。 3. 编写测试检查 [7.4.2 节](#the-flash)实现的闪现消息。测试写得多详细由你自己决定,可以参照[代码清单 7.33](#listing-flash-test),把 `FILL_IN` 换成适当的代码。(即便不测试闪现消息的内容,只测试有正确的键也很脆弱,所以我倾向于只测试闪现消息不为空。) 4. [7.4.2 节](#the-flash)说过,[代码清单 7.25](#listing-layout-flash) 中闪现消息的 HTML 有点乱。换用[代码清单 7.34](#listing-layout-flash-content-tag) 中的代码,运行测试组件,确认使用 `content_tag` 辅助方法之后效果一样。 ##### 代码清单 7.31:为 `gravatar_for` 辅助方法添加一个哈希参数 app/helpers/users_helper.rb ``` module UsersHelper # 返回指定用户的 Gravatar def gravatar_for(user, options = { size: 80 }) gravatar_id = Digest::MD5::hexdigest(user.email.downcase) size = options[:size] gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}" image_tag(gravatar_url, alt: user.name, class: "gravatar") end end ``` ##### 代码清单 7.32:错误消息测试的模板 test/integration/users_signup_test.rb ``` require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "invalid signup information" do get signup_path assert_no_difference 'User.count' do post users_path, user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } end assert_template 'users/new' assert_select 'div#<CSS id for error explanation>' assert_select 'div.<CSS class for field with error>' end . . . end ``` ##### 代码清单 7.33:闪现消息测试的模板 test/integration/users_signup_test.rb ``` require 'test_helper' . . . test "valid signup information" do get signup_path name = "Example User" email = "user@example.com" password = "password" assert_difference 'User.count', 1 do post_via_redirect users_path, user: { name: name, email: email, password: password, password_confirmation: password } end assert_template 'users/show' assert_not flash.FILL_IN end end ``` ##### 代码清单 7.34:使用 `content_tag` 编写网站布局中的闪现消息 app/views/layouts/application.html.erb ``` <!DOCTYPE html> <html> . . . <% flash.each do |message_type, message| %> <%= content_tag(:div, message, class: "alert alert-#{message_type}") %> <% end %> . . . </html> ```