2012-08-02 90 views
1

的用戶我正在使用rspec測試我的應用程序,我讀到我必須在測試環境中創建用戶,但不知道如何......這裏是代碼:ActiveRecord :: RecordNotFound:找不到id =

require 'spec_helper' 

    describe CarsController do 
    describe "GET 'new'" do 
      it "should be successful" do 
      visit new_user_car_path(:user_id=>"28")#also try (current_user) but nothing 
      response.should be_success 
      end 
     end 
    end 

當我運行它,如果你需要更多的代碼,告訴我

編輯我得到這個消息

Failure/Error: visit new_user_car_path(:user_id=>"28") 
ActiveRecord::RecordNotFound: 
    Couldn't find User with id=28 
# ./app/controllers/cars_controller.rb:3:in `new' 
# ./spec/controllers/tanking_logs_controller_spec.rb:6:in `block (3 levels) in <top (required)>' 

。我想這

require 'spec_helper' 

describe CarsController do 
describe "GET 'new'" do 
    it "should be successful" do 
     #user = User.create(...) 
     @user = {:email => "[email protected]", :password => "foobar", :password_confirmation => "foobar" } 
     visit new_user_car_path(@user) 
     response.should be_success 
    end 
end 
end 

,現在我得到這個錯誤:

No route matches {:action=>"new", :controller=>"cars", :email=>"[email protected]", :password=>"foobar", :password_confirmation=>"foobar"} 

回答

3

您沒有ID爲28用戶在您的測試數據庫。您需要爲測試數據庫建立種子並使用您認識的用戶的ID。

另外,根據需要創建一個新用戶:

describe "GET 'new'" do 
    it "should be successful" do 
    user = User.create(...) 
    visit new_user_car_path(user)#also try (current_user) but nothing 
    response.should be_success 
    end 
end 
+0

你的方式更清晰給我解釋一下嗎? – Asantoya17 2012-08-02 18:57:44

+1

你有三個數據庫:開發,生產,測試。您正在搜索的記錄存在於開發數據庫中,但不存在於您的測試數據庫中。所以你必須在測試數據庫中創建對象。或者,您可以將測試數據庫更改爲您的開發數據庫,​​但不建議這樣做,因爲您希望將測試數據庫關閉。 – brntsllvn 2015-04-19 17:18:03

0

現在,你的天賦改變你得到一個路由錯誤。

發生了什麼事是Rails是試圖創造汽車的新汽車,你有#新(這意味着cars_controllernew行動,但你沒有這條路。

運行rake routes看什麼路線和張貼。

1

這可能讓你和運行,但絕不是運行測試的好辦法。

所以,如果你在你的開發數據庫與ID = 28的用戶,您可以告訴Rspec對這個db運行測試,而不是默認的測試db。

在你spec_helper.rb 替換此

ENV["RAILS_ENV"] ||= 'test' 

隨着

ENV["RAILS_ENV"] ||= 'development' 
+2

我不會推薦這樣做。 – dylanjha 2012-08-02 19:19:16

相關問題