使用 Shoulda redirect_to 来测试控制器的创建操作
我正在使用 RSpec + Shoulda 来测试 Rails 3 中的 RESTful 控制器。我无法弄清楚如何测试创建操作的重定向。标准 RESTful 控制器应重定向到新帖子的显示操作。例如,如果我有一个用于项目模型的 ProjectsController,那么在成功创建后,该操作应该:
redirect_to project_url(@project)
应该提供一个方便的 redirects_to 宏来处理这个问题。这是我尝试过的:(
describe ProjectsController, '#create' do
context "Anonymous user" do
before :each do
@attrs = Factory.attributes_for(:project_with_image)
post :create, :project => @attrs
end
it { should assign_to(:project) }
it { should respond_with(:redirect) }
it { should redirect_to(@project) }
end
end
是的,我正在使用 FactoryGirl,但由于在这种情况下我只将它用于属性,所以这应该不重要。我认为。)
我如何指定那里的最后一个测试?它应该redirect_to(...) 什么?我尝试过@project,project_url(@project)..但我无法弄清楚。
查看Shoulda匹配器代码,我注意到redirect_to匹配器可以接受一个块。但我不确定如何访问该块中新创建的 @project 对象...
有什么想法吗?
I'm using RSpec + Shoulda to test my RESTful controller in Rails 3. I'm having trouble figuring out how to test the create action's redirect. The standard RESTful controller should redirect to the show action for the new post. For example, if I have a ProjectsController for a Project model, then upon successful create, that action should:
redirect_to project_url(@project)
Shoulda provides a handy redirects_to macro for handling this. Here is what I have tried:
describe ProjectsController, '#create' do
context "Anonymous user" do
before :each do
@attrs = Factory.attributes_for(:project_with_image)
post :create, :project => @attrs
end
it { should assign_to(:project) }
it { should respond_with(:redirect) }
it { should redirect_to(@project) }
end
end
(Yes, I'm using FactoryGirl, but since I'm only using it for attributes in this case, it shouldn't matter. I think.)
How do I specify the last test there? It should redirect_to(...) what? I've tried @project, project_url(@project).. But I can't figure it out.
Looking at the Shoulda matcher code, I noticed that the redirect_to matcher can accept a block. But I'm not sure how to access the newly created @project object in that block...
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
还没有尝试过,但问题可能是,@project 在您的规范中不可用。怎么样
or
?
Haven't tried it, but the problem probably is, that @project is not available in your spec. How about
or
?