1

我有带有 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

水豚特点:

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
4

1 回答 1

6

此规范将始终失败。

let在 RSpec 中是延迟加载。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
于 2015-07-01T21:13:35.797 回答