我正在使用rspec來測試我的模型方法。一切都很順利,但突然間女工構建不起作用。這裏是我的代碼:rspec之前(:每個)使用factorygirl創建模型不起作用
require File.dirname(__FILE__) + '/../spec_helper'
describe User do
describe 'creation' do
before(:each) do
@user = FactoryGirl.build(:user)
end
it 'is invalid without an email address' do
user = @user
user.email = nil
user.should_not be_valid
end
it 'is invalid without a password' do
user = @user
user.password = nil
user.should_not be_valid
end
it 'is invalid with an invalid email' do
user = @user
user.email = "[email protected]"
user.should_not be_valid
end
it 'is valid with a valid email and password' do
user = @user
user.should be_valid
end
end
describe "method" do
before(:each) do
@user = FactoryGirl.build(:user)
end
context "first_name" do
it "should return the user's first name" do
user = @user
user.first_name.should == "User"
end
end
context "count_of_invoices_by_year" do
# @todo not sure how to check these since .count doesn't work
it "should return the correct count of all invoices in the specified year" do
# there are two invoices in 2013
# user = @user
# user.count_of_invoices_by_year("2013", :total).should == 2
end
it "should return the correct count of paid invoices in the specified year" do
user = @user
debugger
end
it "should return the correct count of sent invoices in the specified year" do
end
end
context "sum_of_invoices_by_year" do
it "should return the sum of the grand_totals of each of the invoices in the specified year" do
# user.sum_of_invoices_by_year("2013", :total).should ==
end
it "should return the sum of the grand_totals of each of the paid invoices in the specified year" do
end
it "should return the sum of the grand_totals of each of the sent invoices in the specified year" do
end
end
end
end
所有其他@user已正確設置和工作,但是當我來到這裏下來:
它「應該返回付款的發票的正確的計數在指定的一年」做 用戶= @user 調試 結束
的factorygirl.build是行不通的。我試圖把每個人都包括在特定的測試中......但它不會設置爲@user。我錯過了什麼?這是錯誤:
NameError Exception: undefined local variable or method `user' for #<RSpec::Core::Example:0x007fc9ec7d4890>
當我嘗試看看用戶因爲@user是零
你的代碼似乎沒問題。試着嘗試一下。除了引發異常並嘗試運行rspec之外的所有測試。如果不再增加,請嘗試逐步添加測試以找出造成問題的原因 – ted
這甚至不是導致問題的測試。它實際上並沒有真正創建用戶 –
顯然,它不是FactoryGirl本身,因爲它與rspec一起使用。 (除了它在其他測試中工作,所以你可以認爲其原因與rspec相關) – ted