Rspec控制器测试 - 意外错误/不确定如何处理它

时间:2015-11-29 05:27:59

标签: ruby-on-rails rspec

我将此测试用于FacultiesController

describe FacultiesController do
  describe "GET show" do
    it "responds successfully with an HTTP 200 status code" do
      get :show
      expect(response).to be_success
      expect(response).to have_http_status(200)
    end
  end

  describe "GET index" do
    it "responds successfully with an HTTP 200 status code" do
      get :index
      expect(response).to be_success
      expect(response).to have_http_status(200)
    end
  end
end

输出:

故障:

  1) FacultiesController GET show responds successfully with an HTTP 200 status code
     Failure/Error: get :show

     ActionController::UrlGenerationError:
       No route matches {:action=>"show", :controller=>"faculties"}
     # ./spec/controllers/faculties_controller_spec.rb:5:in `block (3 levels) in <top (required)>'

  2) FacultiesController GET index responds successfully with an HTTP 200 status code
     Failure/Error: @faculties=Faculty.where(:university_id => @university.id).all

     NoMethodError:
       undefined method `id' for nil:NilClass
     # ./app/controllers/faculties_controller.rb:5:in `index'
     # ./spec/controllers/faculties_controller_spec.rb:13:in `block (3 levels) in <top (required)>'

1)当我运行rake routes时,我看到了

faculty GET    /faculties/:shortcut(.:format)                      faculties#show

所以,我想我需要用这个GET指定快捷方式。但是如何?

我尝试添加:shortcut=>"test",但这不起作用,也尝试了params: {:shortcut=>"test"}。在我写"GET faculties/test"也删除行 get :show之前,没有任何作用。

这是应该的吗?

2)

Failure/Error: @faculties=Faculty.where(:university_id => @university.id).all

         NoMethodError:
           undefined method `id' for nil:NilClass

首先,它再次在浏览器测试中运行良好。我使用模块帮助控制器通过子域定义@university

如何通过此测试?我应该提供一些获得索引的选项吗?顺便说一句,它全部在我的factories.rb文件中定义,因为子域字符串存储在db中。

我可能会在describe之前调用此规范中的工厂新实例?

university = create(:university)
faculty = create(:faculty)

提前致谢。

1 个答案:

答案 0 :(得分:1)

1)你应该创建一个新的教师并传递它的id

describe "GET show" do
  let(:faculty) {FactoryGirl.create(:faculty)}
  it "responds successfully with an HTTP 200 status code" do
     get :show, :id => faculty.id #or get :show, :shortcut => faculty.id
    expect(response).to be_success
    expect(response).to have_http_status(200)
  end
end

2)你应该创建教师和大学&amp;把它作为params传递

describe "GET index" do
  let(:university) {FactoryGirl.create(:university)}
  before(:each) do
    FactoryGirl.create(:faculty, :university_id => university.id)  
  end 
  it "responds successfully with an HTTP 200 status code" do
    get :index, university_id => university.id
    expect(response).to be_success
    expect(response).to have_http_status(200)
  end
end

请提供索引路线,如果它不起作用