2013-06-29 38 views
0

我一直在Rails 3.2中使用測試工作流幾個月,我從Rem Zolotykh的截屏中找到了。這對於驗證Rails堆棧的基本組件非常簡單而且非常有用。但是,我第一次在Rails 4.0.0中使用它,並且我得到了一個訂單依賴性錯誤,我之前沒有訂單依賴性錯誤。這是UsersController規格:RSpec「未定義的方法」順序依賴關係在Rails 3.2規範中的依賴關係錯誤3.2

需要 'spec_helper'

describe UsersController do 
    describe 'POST create' do 
    let!(:user) { stub_model(User) } 
    it 'sends new message to User class' do # this is the one that fails intermittently 
     params = {       # call this spec 1 
     'first_name' => 'Test', 
     'last_name' => 'Tester', 
     'email_address' => '[email protected]', 
     'password' => 'secret', 
     'password_confirmation' => 'secret' 
     } 
     User.stub(:new).and_return(user) 
     User.should_receive(:new).with(params) 
     post :create, user: params 
    end 
    it 'sends save message to user model' do # this one always passes 
     User.stub(:new).and_return(user)  # call this spec 2 
     user.should_receive(:save) 
     post :create 
    end 
    end 
end 

這是UsersController:

class UsersController < ApplicationController 
    def new 
    @user = User.new 
    end 

    def create 
    user = User.new(params[:user]) 
    user.save 
    render nothing: true 
    end 
end 

應該很簡單。 但是,當隨機測試訂單首先觸發規格2時,則規格1通過。如果規範1首先被觸發,它將失敗,但規範2仍然通過。 爲規範1失敗錯誤:

1) UsersController POST create sends new message to User class 
Failure/Error: post :create, user: params 
NoMethodError: 
    undefined method `save' for #<User:0x007f9d1b6baf98> 
# ./app/controllers/users_controller.rb:8:in `create' 
# ./spec/controllers/users_controller_spec.rb:32:in `block (3 levels) in <top (required)>' 

我使用rspec的核心2.13.1和RSpec護欄2.13.2。 我搜索了高和低,我什麼也沒找到。 有什麼建議嗎?

回答

0

是的,我認爲是。

在情況1中,User.new已被樁接以返回memoized stub_model。但是,存根模型沒有save方法,因此在執行post :create時會出錯,然後調用new,然後對結果調用save

如果您執行第二個規格1st,它會在stub_model上創建save將被調用的期望,因此情況1會通過。

我很困惑的是,let不應該跨越示例緩存結果,如https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let中所述,所以我認爲即使情況2先執行,情況1仍應該失敗。

至於爲什麼這將在3.2和4.0之間不同,我不知道。祝你好運。