RSpec,Factory Girl和Capybara:没有保存任何物品

时间:2015-07-01 20:45:44

标签: ruby-on-rails rspec capybara factory-bot database-cleaner

我有RSpec的可安装Rails引擎:

RSpec.configure do |config|
  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do |example|
    DatabaseCleaner.strategy= example.metadata[:js] ? :truncation : :transaction
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

简单工厂:

FactoryGirl.define do
  factory :post, :class => MyEngine::Post do
    title 'title'
  end
end

Capybara功能:

require 'spec_helper'

describe 'Post', :type => :feature do
  let(:post) { FactoryGirl.create :post }

  it 'index action should have post' do
    visit posts_path
    expect(page).to have_text(post.title)
  end
end

Post模型没有任何验证。

但是当我运行测试时,它表明没有创建帖子。

同样是ActiveRecord日志:

INSERT INTO "my_engine_posts" ...
RELEASE SAVEPOINT active_record_1
rollback transaction

1 个答案:

答案 0 :(得分:6)

此规范将始终失败。

RSpec中的

let是延迟加载的。在您引用它之前,实际上并未创建post

expect(page).to have_text(post.title)

因此,您可以在访问该页面之前使用不是延迟加载的let!或引用post

require 'spec_helper'

describe 'Post', :type => :feature do
  let(:post) { FactoryGirl.create :post }

  it 'index action should have post' do
    post
    visit posts_path
    expect(page).to have_text(post.title)
  end
end