简体   繁体   English

RSpec +工厂女孩测试404 ActiveRecord :: RecordNotFound

[英]RSpec + Factory Girl Test 404 ActiveRecord::RecordNotFound

I have this in my controller spec file 我的控制器规格文件中有这个

it "should raise 404" do
      business = FactoryGirl.build(:business)
      expect{get :edit, :id => business}.to raise_error(ActiveRecord::RecordNotFound)
    end

if I am right, build does not save to the database, so business should not exist, and my test should pass, but it does not. 如果我是对的,则构建不会保存到数据库,因此业务不应该存在,并且我的测试应该通过,但事实并非如此。

I also tried a string as a value of "id", but it still fails. 我也尝试将字符串作为“ id”的值,但是仍然失败。

I have tried with this controller action: 我已经尝试使用此控制器操作:

def edit
    if params[:id].to_i == 0
      name = params[:id].to_s.titleize
      @business = Business.find_by_name!(name)
    else
      @business = Business.find(params[:id])
    end
    respond_with(@business)
  end

an ID that does not exist, and it does indeed show a 404. 一个不存在的ID,并且确实显示404。

If you ask why a condition like that, I also make this action respond to a string for the "id" param. 如果您问为什么这样的条件,我还将使此操作响应“ id”参数的字符串。

Any ActiveRecord::RecordNotFound is received by this code in the application controller: 此代码在应用程序控制器中接收到任何ActiveRecord :: RecordNotFound:

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

  private
    def record_not_found
      render :text => "404 Not Found Baby!", :status => 404
    end

why is my test for a 404 not passing? 为什么我的404测试不及格?

Your controller does not raise ActiveRecord::RecordNotFound exception, it rescues from it in ApplicationController. 您的控制器不会引发ActiveRecord::RecordNotFound异常,而是在ApplicationController中从中抢救异常。 So try to test for response code or text, something like 因此,请尝试测试响应代码或文本,例如

  it "should respond with a 404" do
    business = FactoryGirl.build(:business)
    get :edit, :id => business
    response.response_code.should == 404
  end

I know I'm late to the party, but you shouldn't really be creating records in controller tests. 我知道我迟到了,但是您不应该在控制器测试中真正创建记录。 You create records in model tests. 您在模型测试中创建记录。

In your controller tests, if you are expecting a create to fail, stub it with something like my_model.stub(:save).and_return(false) . 在控制器测试中,如果您期望创建失败,请使用my_model.stub(:save).and_return(false)类的东西对它进行存根。 If you are expecting create to be successful, you could stub it with my_model.stub(:save).and_return(true) 如果期望创建成功,则可以使用my_model.stub(:save).and_return(true)将其存根。

Using Shoulda.... 正在使用Shoulda ...

context "record valid" do
  before :each do
    my_model.stub(:save).and_return(true)
    post :create
  end
  it { should redirect_to(dashboard_url) }
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM