使用RSpec,Devise,Factory Girl测试控制器

Mik*_*ike 5 testing controller rspec ruby-on-rails factory-bot

我有模特:帖子和用户(设计).我正在测试控制器Post.

describe "If user sign_in" do

   before(:all){ 
     @user = Factory(:user)
   }

   it "should get new" do
     sign_in @user  
     get 'new'
     response.should be_success
     response.should render_template('posts/new')
   end

   it "should create post" do
     sign_in @user
     post 'create', :post => Factory(:post)
     response.should redirect_to(post_path(:post))
   end
 end  
Run Code Online (Sandbox Code Playgroud)

但第二次测试失败了:

失败/错误:发布'创建',:发布=>工厂(:发布)ActiveRecord :: RecordInvalid:验证失败:已收到电子邮件,已收到电子邮件,已取得用户名

我该如何解决?

con*_*are 9

你不需要另外的宝石.FactoryGirl为此建立了动态​​助手.我建议观看关于此的简短Railscast.以下是它如何工作的片段:

FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "foo#{n}" }
    password "foobar"
    email { "#{username}@example.com" }
Run Code Online (Sandbox Code Playgroud)

  • 如果您是rails开发人员而不使用Railcast,那么您做错了. (18认同)

luc*_*tte 7

您需要一个工具来在测试之间清理数据库.因为您应该能够使用干净的数据库运行每个测试.我正在使用database_cleaner,它是一个非常着名的宝石,它的效果非常好.它也很容易设置.README(RSpec相关)的一个例子:

RSpec.configure do |config|

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

  config.before(:each) do
    DatabaseCleaner.start
  end

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

end
Run Code Online (Sandbox Code Playgroud)

  • 当我在spec_helper中包含您的代码时.我收到错误失败/错误:无法从backtrace中找到匹配的行ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:无法在事务中启动事务:begin transaction (3认同)
  • 我发现SQLite异常解决方案是删除`clean_with(:truncation)`并将策略完全更改为`DatabaseCleaner.strategy =:truncation` (3认同)