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