使用 Shoulda redirect_to 来测试控制器的创建操作

发布于 2024-10-16 21:28:50 字数 871 浏览 8 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

悲欢浪云 2024-10-23 21:28:50

还没有尝试过,但问题可能是,@project 在您的规范中不可用。怎么样

it {should redirect_to(Project.last) }

or

it {should redirect_to(assigns(:project)) }

?

Haven't tried it, but the problem probably is, that @project is not available in your spec. How about

it {should redirect_to(Project.last) }

or

it {should redirect_to(assigns(:project)) }

?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文