我在railstutorial.org第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: "user@example.com"
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('user@example.com') }
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结果为零。有什么想法吗?
谢谢!
答案 0 :(得分:1)
如果不详细检查您的代码以了解所有内容的背景,那么user.name
不会返回nil
,而user
是nil
,因此没有方法/属性name
,如下所示:
undefined method `name' for nil:NilClass
在定义符号:user
:
let(:user) { User.find_by_email('user@example.com') }
但是你在测试中引用了对象user
:
it { should have_selector('title', text: user.name) }
将前一个符号:user
更改为user
,您的测试应该通过。