RSpec,工厂女孩和水豚:没有项目保存(RSpec, Factory Girl and Capybara: no items saved)
我有可安装的带有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 endPost模型没有任何验证。
但是当我运行测试时,它显示没有创建任何帖子。
还有ActiveRecord日志:
INSERT INTO "my_engine_posts" ... RELEASE SAVEPOINT active_record_1 rollback transactionI have mountable Rails engine with RSpec:
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 endSimple factory:
FactoryGirl.define do factory :post, :class => MyEngine::Post do title 'title' end endCapybara feature:
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 endAnd Post model doesn't have any validations.
But when i running tests it shows that there is no posts created.
Also ActiveRecord logs:
INSERT INTO "my_engine_posts" ... RELEASE SAVEPOINT active_record_1 rollback transaction最满意答案
这个规范总是会失败。
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 endThis spec will always fail.
let in RSpec is lazy loading. post is not actually created until you reference it in:
expect(page).to have_text(post.title)So you can either use let! which is not lazy loading or reference post before you visit the page:
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更多推荐
发布评论