0
我在railstutorial.org的第7章中練習4時遇到了問題。Rails教程第7章練習4
下面是測試:
describe "signup" do
before { visit signup_path }
describe "with invalid information" do
it "should not create a user" do
expect { click_button "Create my Account".not_to change(User, :count) }
end
end
describe "error messages" do
before { click_button "Create my account" }
it { should have_selector('title', text: "Sign up") }
it { should have_content('error') }
end
describe "with valid information" do
before do
fill_in "Name", with: "Example User"
fill_in "Email", with: "[email protected]"
fill_in "Password", with: "foobar"
fill_in "Confirmation", with: "foobar"
end
it "should create a user" do
expect do
click_button "Create my account"
end.to change(User, :count).by(1)
end
end
describe "after saving the user" do
before { click_button "Create my account" }
let(:user) { User.find_by_email('[email protected]') }
it { should have_selector('title', text: user.name) }
it { should have_selector('div.alert.alert-success', text: 'Welcome') }
end
end
這裏是它應該測試,users_controller.rb:
def create
@user = User.new(params[:user])
if @user.save
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
這裏的show.html.erb代碼以及:
<% provide(:title, @user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for @user %>
<%= @user.name %>
</h1>
</section>
</aside>
</div>
當我運行我的測試時,我得到這個:
$ bundle exec rspec spec/requests/user_pages_spec.rb
........FF
Failures:
1) User Pages signup after saving the user
Failure/Error: it { should have_selector('title', text: user.name) }
NoMethodError:
undefined method `name' for nil:NilClass
# ./spec/requests/user_pages_spec.rb:57:in `block (4 levels) in <top (required)>'
2) User Pages signup after saving the user
Failure/Error: it { should have_selector('div.alert.alert-success', text: 'Welcome') }
expected css "div.alert.alert-success" with text "Welcome" to return something
# ./spec/requests/user_pages_spec.rb:58:in `block (4 levels) in <top (required)>'
Finished in 0.86152 seconds
10 examples, 2 failures
Failed examples:
rspec ./spec/requests/user_pages_spec.rb:57 # User Pages signup after saving the user
rspec ./spec/requests/user_pages_spec.rb:58 # User Pages signup after saving the user
它應該將測試用戶保存到測試數據庫,但由於某種原因,user.name變爲零。有任何想法嗎?
謝謝!
感謝您的回覆。我想到了。 「保存用戶後」做結束塊超出了「有效信息」塊的範圍,因此表單沒有被填充(這是nil的來源)。我在「有效信息」塊中放入「保存用戶塊後」,並通過測試。只是爲了回覆,我會將您的答案標記爲已接受。 :-) – dartfrog 2012-04-03 22:06:10
啊,很好隨意寫在答案中,並接受你自己的,所以如果別人在這個同樣的問題上絆倒,他們知道他們會出錯:) – djlumley 2012-04-03 23:30:37
你是對的,問題是零'user'而不是'nil'user.name',但是提出的解決方案是不正確的。在'let'中使用符號':user'會自動創建一個名爲'user'的局部變量。有關更多信息,請參閱[Rails教程示例應用參考實現](https://github.com/railstutorial/sample_app_2nd_ed)。 問題可能是,用戶使用電子郵件'user @ example.com'某種程度上不會被'click_button'命令創建。我不知道這是爲什麼,但作爲一種解決方法,您可以對該名稱進行硬編碼,用「Example User」替換'user.name'。 – mhartl 2012-06-07 16:51:21