这是我当前的users_controller_spec.rb文件
require 'spec_helper'
describe UsersController do
render_views
.
.
.
describe "success" do
before(:each) do
@attr = { :name => "New User", :email => "user@example.com",
:password => "foobar", :password_confirmation => "foobar" }
end
it "should create a user" do
lambda do
post :create, :user => @attr
end.should change(User, :count).by(1)
end
it "should redirect to the user show page" do
post :create, :user => @attr
response.should redirect_to(user_path(assigns(:user)))
end
end
end
end
当我运行时,我得到以下内容:
Failures:
1) UsersController POST 'create' success should redirect to the user show page
Failure/Error: response.should redirect_to(user_path(user))
ActionController::RoutingError:
No route matches {:action=>"show", :controller=>"users"}
# ./spec/controllers/users_controller_spec.rb:95:in `block (4 levels) in <top (required)>'
这让我相信:用户不是一个真实的对象。我如何测试这个以及如何将用户更改为user_path可以理解的对象。
提前感谢您的帮助。
更新:
def create
@title = "Sign up"
@user = User.new(params[:user])
if @user.save
redirect_to @user, :notice => "Signed Up!"
else
@title = "Sign up"
render "new"
end
end
当我运行以下内容时:
it "should redirect to the user show page" do
post :create, :user => @attr
user = assigns(:user)
user.should_not be_blank
puts "user errors are: #{user.errors.full_messages.inspect}" unless user.is_valid?
user.should be_valid
response.should redirect_to(user_path(user))
end
我明白了:
1) UsersController POST 'create' success should redirect to the user show page
Failure/Error: user.should_not be_blank
expected blank? to return false, got true
# ./spec/controllers/users_controller_spec.rb:94:in `block (4 levels) in <top (required)>'
答案 0 :(得分:4)
尝试使用assigns
括号而不是括号。
assigns[:user]
修改强>
我在测试控制器操作时总是使用的一种模式是确保分配相关视图所需的变量。例如,
it "should assign an @user variable" do
post :create, :user => @attr
assigns[:user].should_not be_nil
assigns[:user].should be_kind_of(User)
end
答案 1 :(得分:2)
你有一个错字
response.should redirect_to(user_path(:user))
应该是
response.should redirect_to(user_path(user))
编辑: 尝试检查用户是否有效:
it "should redirect to the user show page" do
post :create, :user => @attr
user = assigns(:user)
user.should_not be_blank
puts "user errors are: #{user.errors.full_messages.inspect}" unless user.is_valid?
user.should be_valid
response.should redirect_to(user_path(user))
end
我知道它适用于之前的测试用例...但仍然值得在这里至少进行一次广泛检查。你可以在确定时删除所有的guff。
答案 2 :(得分:2)
在你的测试中:
it "should redirect to the user show page" do
@user = Factory(:user)
post :create, :user => @attr
user = assigns(:user)
response.should redirect_to(user_path(@user))
end
您的@attr
哈希与@user不同。您正在创建具有@attr属性的用户,并断言它应该重定向到@user show(与创建的不同)。改为:
it "should redirect to the user show page" do
post :create, :user => @attr
user = assigns(:user)
response.should redirect_to(user_path(user))
end