为什么 rspec 重定向在测试期间无法获取完整路由?

发布于 2024-09-27 10:31:17 字数 850 浏览 6 评论 0原文

我正在尝试对控制器进行以下功能测试。我正在使用以下

  • RSpec2
  • Rails 3
  • Shoudla
  • Mocha

这是测试

context "POST on create should be successful" do
  before(:each) do
    Model.any_instance.expects(:save).returns(true).once
    Model.any_instance.stubs(:id).returns(1)
    post :create, :model => {}
  end

  it { should assign_to(:model).with_kind_of(Model) }
  it { should set_the_flash.to("Model was created successfully.")}
  it { should redirect_to(model_path(1))}
end

,被测试的控制器是

def create
  @model = Model.new(params[:model])

  if @model.save
    flash[:success] = "Model was created successfully."
  end
  respond_with @model
end

唯一失败的测试是第三个测试,它表示返回的路径是“http://test.host/models”而不是“ http://test.host/models/1”

当我在浏览器中运行应用程序时,我得到了正确的重定向。

I'm attempting the following functional test on the controller. I'm using the following

  • RSpec2
  • Rails 3
  • Shoudla
  • Mocha

Here's the test

context "POST on create should be successful" do
  before(:each) do
    Model.any_instance.expects(:save).returns(true).once
    Model.any_instance.stubs(:id).returns(1)
    post :create, :model => {}
  end

  it { should assign_to(:model).with_kind_of(Model) }
  it { should set_the_flash.to("Model was created successfully.")}
  it { should redirect_to(model_path(1))}
end

and the controller under test is

def create
  @model = Model.new(params[:model])

  if @model.save
    flash[:success] = "Model was created successfully."
  end
  respond_with @model
end

The only failing test is the third test which says that the path getting returned is "http://test.host/models" instead of "http://test.host/models/1"

When I'm running the application in the browser I am getting the correct redirection.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

天荒地未老 2024-10-04 10:31:17

我认为你也需要模拟 to_params 。由路由系统使用

context "POST on create should be successful" do
  before(:each) do
    Model.any_instance.expects(:save).returns(true).once
    Model.any_instance.stubs(:id).returns(1)
    Model.any_instance.stubs(:to_params).returns(1)
    post :create, :model => {}
  end

  it { should assign_to(:model).with_kind_of(Model) }
  it { should set_the_flash.to("Model was created successfully.")}
  it { should redirect_to(model_path(1))}
end

I think you need mock to_params too. It's use by route system

context "POST on create should be successful" do
  before(:each) do
    Model.any_instance.expects(:save).returns(true).once
    Model.any_instance.stubs(:id).returns(1)
    Model.any_instance.stubs(:to_params).returns(1)
    post :create, :model => {}
  end

  it { should assign_to(:model).with_kind_of(Model) }
  it { should set_the_flash.to("Model was created successfully.")}
  it { should redirect_to(model_path(1))}
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文