使用 RSpec 和 Rails 进行 TDD:在没有视图的情况下测试控制器操作
当我继续使用 RSpec 2 和 Rails 3.1 学习 TDD 时,我似乎找不到解决这个问题的方法。
我有一个具有新操作和创建操作的用户控制器。在我的 UsersController 规范中,我有
users_controller_spec.rb
describe "POST 'create'" do
before(:each) do
@attr = Factory.attributes_for(:user)
end
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
end
,在我的 UsersController 中,
users_controller.rb
def create
@user = User.new(params[:user])
end
此规范失败,
1) UsersController POST 'create' should assign an @user variable
Failure/Error: post :create, :user => @attr
ActionView::MissingTemplate:
我可以继续实现应用程序代码以使此测试通过,但我觉得这个测试应该按原样通过。
有什么建议吗?
As I continue to learn my way around TDD with RSpec 2 and Rails 3.1, I can't seem to find a solution to this problem.
I have a Users controller with a new and create action. In my UsersController spec, I have
users_controller_spec.rb
describe "POST 'create'" do
before(:each) do
@attr = Factory.attributes_for(:user)
end
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
end
and in my UsersController,
users_controller.rb
def create
@user = User.new(params[:user])
end
This spec is failing with
1) UsersController POST 'create' should assign an @user variable
Failure/Error: post :create, :user => @attr
ActionView::MissingTemplate:
I can continue to implement application code to get this test to pass, but I feel like this test should be passing as it is.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的
create
方法需要执行某些操作。渲染模板或重定向。由于您没有告诉它重定向,所以它假设您希望它呈现模板,但是当它找不到create.html.erb
文件时,它会抛出错误。你最好的选择是这样做:
或这样做:
Your
create
method needs to do something. Either render a template or redirect. Since you're not telling it to redirect it's assuming that you want it to render a template but when it can't find acreate.html.erb
file it throws an error.You're best bet is to do either this:
or this:
要测试渲染您不需要的内容:
To test rendering nothing you'll want:
我自己最近也遇到过这个情况。似乎一种可能性是挽救测试中的错误。
我不知道这个解决方案有多“正确”。一方面,它绝对强调“一次测试一件事”的心态,另一方面,它看起来有点丑陋。
编辑
我想你可以在你的规范助手中制作一些漂亮的包装器,比如
I've come across this recently myself. It seems one possibility would be to rescue the error in your test.
I don't know how "correct" this solution is. On one hand, it definitely emphasizes the "testing one thing at a time" mentality, on the other, it seems kind of ugly.
Edit
I suppose you could make some nice wrappers in your spec helper, something like