[英]Ruby on Rails RSPEC
我正在通過Rails教程學習Rails。 作者積極教導RSpec的選擇性位。 在每一章之后的練習中,您都有機會學習編寫更加實用的代碼。 我選擇做那些練習。 但是,問題在於,在接下來的章節中,他會將讀者當作沒有閱讀者一樣對待,因此,當您不知道如何適應他所寫的新的“笨拙”代碼時,您編寫的更雄辯的代碼很容易遇到挑戰。它是“ pithier”對應物。
在精簡版本中,文件的開頭使其自身的重復次數減少了,看起來像這樣:
require 'spec_helper'
describe User do
before { @user = User.new(name: "Example User", email: "user@example.com",
password: "foobar", password_confirmation: "foobar") }
subject { @user }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation )}
it { should be_valid }
.
.
.
end
因此,我們的測試如下所示:
describe "when email is not present" do
before { @user.email = " " }
it { should_not be_valid }
end
嘗試創建是否存在@user.password
和@user.password_confirmation
的測試時,我希望繼續使用此RSpec格式。
作者版本如下所示:
describe "when email is not present" do
before do
@user= User.new(name: "Example User", email: "user@example.com",
password: " ", password_confirmation = " ")
end
it { should_not be_valid }
end
我的嘗試(因為作者恢復了做事的方法而無需使用更專業的RSpec代碼)將是這樣的:
describe "when password is not present" do
before { @user.password = " ", @user.password_confirmation = " " }
it { should_not be_valid }
end
在這種情況下,這是使用before修改多個哈希值的正確方法嗎?
此外,我正在努力尋找有關RSpec問題的答案。 有沒有人有找到這類答案的可靠程序?
通常,如果您的一個塊占用多行,則應使用do...end
而不是{ }
,因此您的代碼如下所示:
describe "when password is not present" do
before do
@user.password = " "
@user.password_confirmation = " "
end
it { should_not be_valid }
end
在尋找與rSpec有關的問題的答案時,我通常會先轉向Google,但我建議嘗試縮小搜索范圍(例如,如果您使用的是rSpec和Capybara,請查看Capybara文檔,因為我還沒有找到rSpec文檔會很有幫助)。 接下來,我會像您一樣看這里,所以我認為您的方向正確。
在作者版本中, before
塊還創建了一個實例變量@user
用於輸入每個it
描述。 創建多個哈希值應放在某個方法的參數中,例如: def some_method(args, hash_options = {})
。 將哈希參數放入方法中,而不是before
塊before
放入Rspec中,這是一種紅寶石樣式。 before
塊用於在進入it
塊之前實例化所需的執行。 因此,在您的情況下,我建議不要只是將多個哈希值放在before
塊中,而是准備一些使用這些哈希參數實例化的對象,以便可以在it
塊中運行該對象。
我建議閱讀該書,以獲得Rspec的概述:
Rspec中的日常Rails測試 ,
https://leanpub.com/everydayrailsrspec
在線資源:
更好的規格
http://betterspecs.org/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.