let(:user){create(:user)}#=>之后记录不存在

时间:2012-04-12 07:53:10

标签: ruby-on-rails rspec factory-bot

我有一个测试用例:

describe User do
  let(:user) { create(:user) } # FactoryGirl
  it { User.count == 1 }  
end

并设置:

RSpec.configure do |config|
  config.include FactoryGirl::Syntax::Methods
  config.before(:suite) { DatabaseCleaner.strategy = :truncation }
  config.before(:each) { DatabaseCleaner.start }
  config.after(:each) { DatabaseCleaner.clean }
  config.use_transactional_fixtures = false
end

为什么它不起作用? 如何使用let并得到一个真正持久的记录?

1 个答案:

答案 0 :(得分:5)

let调用是惰性求值的,除非调用特定方法,否则它们不会运行:

describe User do
  subject { user }
  let(:user) { create(:user) } # FactoryGirl
  it { … }  
end

或者,使用let!作为始终评估的前提条件:

describe User do
  let!(:user) { create(:user) } # FactoryGirl
  it { … }  
end