這裏是我的測試:redirect_to驗證失敗後,可能在軌道?
def test_words_with_non_letters_are_rejected
visit '/plays'
click_link_or_button 'Play New Word'
fill_in 'play[word]', :with => 'boom!'
click_link_or_button 'Play!'
assert page.has_css?("#errors")
fill_in 'play[word]', :with => '37nums'
click_link_or_button 'Play!'
assert page.has_css?("#errors")
fill_in 'play[word]', :with => 'ok'
click_link_or_button 'Play!'
assert_equal '/plays', current_path
end
這裏是我的控制器:
class PlaysController < ApplicationController
def index
@plays = Play.all
end
def new
end
def create
if params[:play][:word].blank?
flash[:error] = 'blank'
redirect_to new_play_path
else
@play = Play.create(plays_params)
redirect_to plays_path
end
end
private
def plays_params
params.require(:play).permit(:word)
end
end
這裏是我的模型:
class Play < ActiveRecord::Base
before_save { self.word = word.downcase }
validates :word, presence: true, length: { maximum: 7 }
# validates_format_of :word, :with =>
def letter_scores
{"A"=>1, "B"=>3, "C"=>3, "D"=>2, "E"=>1, "F"=>4, "G"=>2, "H"=>4, "I"=>1, "J"=>8,
"K"=>5, "L"=>1, "M"=>3, "N"=>1, "O"=>1, "P"=>3, "Q"=>10, "R"=>1, "S"=>1, "T"=>1,
"U"=>1, "V"=>4, "W"=>4, "X"=>8, "Y"=>4, "Z"=>10}
end
def score(setting_hash = {:word_multiplier => :single})
word_multiplier = {:single => 1, :double => 2, :triple => 3}
word.upcase.chars.inject(0){|sum, letter| sum + letter_scores[letter]} * word_multiplier[setting_hash[:word_multiplier]]
end
end
所以我無法寫的validates_format_of驗證的正則表達式的Play模型。此外,我不知道如何驗證失敗後重定向到正確的頁面。我嘗試在創建控制器中寫入兩個redirect_to,但是我得到了一個錯誤消息,其中包含太多redirect_tos。
在其他條件創建操作的,我試過Play.create行之後寫的:
redirect_to plays_path if @play
flash[:error] "Something when wrong during Play creation"
redirect_to new_play_path
我在做什麼錯?