0

我正在使用 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@invalid"
      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 都已正确设置并且可以正常工作,但是当我来到这里时:

它“应该在指定年份返回正确的已付发票数量” do user = @user debugger end

factorygirl.build 不起作用。我试着把它放在每个人身上,包括直接在特定的测试中......但它不会设置为@user。我错过了什么?这是错误:

NameError Exception: undefined local variable or method `user' for #<RSpec::Core::Example:0x007fc9ec7d4890>

当我尝试查看用户时会发生这种情况,因为@user 为零

4

1 回答 1

4

结果发现用户实际上并不存在于测试用例中,除非您实际上尝试用它测试某些东西……这很奇怪。

  it "should return the user's first name" do
    user.first_name.should == "User"
  end

这有用户在场,但这个:

  it "should return the user's first name" do
    debugger
  end

调试器在此处显示 user = nil 后查看控制台。

于 2013-04-14T19:40:42.773 回答