用RSpec、Devise、Factory Girl测试控制器



我有两个模型:Post和User(Devise)。我正在测试控制器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  

但第二次测试失败了:

失败/错误:post"create",:post=>工厂(:post)ActiveRecord::RecordInvalid:验证失败:电子邮件已被占用,电子邮件已被使用,用户名已被使用

我该如何解决这个问题?

您不需要其他宝石。FactoryGirl为此内置了动态助手。我建议你看一下关于这件事的短篇小说《Railscast》。以下是它的工作原理:

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

您需要一个工具来在测试之间清理数据库。因为您应该能够使用干净的数据库运行每个测试。我使用的是database_cleaner,这是一个非常著名的宝石,它运行得非常好。它也很容易设置。自述文件中的一个例子(与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

最新更新