【问题标题】:Why does rspec redirect not get full route during test?为什么 rspec 重定向在测试期间没有得到完整的路由?
【发布时间】:2010-10-14 13:14:24
【问题描述】:

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

  • RSpec2
  • 导轨 3
  • 舒德拉
  • 摩卡

这是测试

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”

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

【问题讨论】:

  • 我没有解决这个问题,我最终通过不使用模拟行为而只使用工厂调用来获得所需的行为来解决问题。因此,如果有人可以解释为什么模拟不正确,请告知。

标签: ruby-on-rails ruby-on-rails-3 factory-bot mocha.js rspec2


【解决方案1】:

我认为您也需要模拟 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

【讨论】:

  • 我仍然得到与附加存根相同的结果。我试图覆盖“to_param”和“to_params”。我认为您的意思是覆盖的“to_param”。
猜你喜欢
  • 1970-01-01
  • 2012-02-12
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2021-01-17
  • 2014-09-16
相关资源
最近更新 更多