2012-09-19 49 views
3

我有模型Price具有以下範圍和屬性。水豚和Rspec沒有範圍

def self.total 
    self.sum(:amount) + self.sum(:tax) 
end 

def self.today 
    where(:date => Date.today) 
end 

def self.for_data 
    where(:bought => true) 
end 

我有範圍鏈獲取當前用戶總量今天。

<p class="today"> 
    Today 
    <span class="amount today"> 
    <%= number_to_currency(current_user.prices.for_data.today.total) %> 
    </span> 
</p> 

我寫了一個規範來測試這個。

# user_pages_spec 

describe 'Overview Page' do 
    it 'shows spending' do 
    make_user_and_login 
    price = FactoryGirl.create(:price) 
    click_link('Overview') 
    page.should have_selector('title', :text => 'Overview') 
    within('p.today', :text => 'Today') do 
     page.should have_content('$1.01') 
    end 
    end 
end 

這是我的價格工廠:

factory :price do 
    amount '1.00' 
    tax '0.01' 
    bought true 
    date Date.today 
end 

不幸的是,這將返回錯誤:

1) UserPages Account Settings Data Page shows spending 
Failure/Error: page.should have_content('$1.01') 
expected there to be content "$1.01" in "\n\t\t\tToday\n\t\t\t$0.00\n\t\t" 

手動放置在視圖作品$1.01而不是當我取決於範圍。它看起來像沒有檢測到工廠或範圍,因爲它返回$0.00。爲什麼以及如何解決這個問題?

謝謝。


支持/ user_macros.rb

module UserMacros 
    def make_user_and_login 
    user = FactoryGirl.create(:user) 
    visit new_user_session_path 
    page.should have_selector('title', :text => 'Login') 
    fill_in('Email', :with => user.email) 
    fill_in('Password', :with => user.password) 
    click_button('Login') 
    page.should have_selector('title', :text => 'Home') 
    end 
end 

回答

2

我認爲問題是,價格記錄不必須與CURRENT_USER關係。所以在這種情況下,current_user的總和真的是0.00。你可以通過改變價格工廠來解決這個問題:

factory :price do 
    amount '1.00' 
    tax '0.01' 
    bought true 
    date Date.today 
    user { User.first || FactoryGirl.create(:user) } 
end 
+0

這沒有做到。另外我使用Devise,如果它有助於使用'current_user'。我相信你不得不使用當前用戶的權利,但我正在環顧四周,無法找到任何相關信息。 – LearningRoR

+1

你可以顯示「make_user_and_login」方法嗎? – railscard

+0

我編輯了我的問題向你展示。 – LearningRoR

1

這是一個集成規格我想,讓你有你的互動步驟(登錄)之前執行你的播種步驟(廠創建)。

你可以做以下的工廠創建過程中照顧戶協會:

user = FactoryGirl.create(:user) 
price = FactoryGirl.create(:price, user: user) 
+0

我把一個'之前(:每個)'塊,它仍然給了我同樣的錯誤。我也嘗試把它放在我的'make_user_and_login'之前並登錄。 – LearningRoR