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

5
我有两个模型: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 => Factory(:post) ActiveRecord :: RecordInvalid: 验证失败:电子邮件已被占用,电子邮件已被占用,用户名已被占用

我该怎么办?

2个回答

9
你不需要为此再使用另一个宝石。FactoryGirl已经内置了动态辅助功能。我建议观看关于此的简短Railscast。以下是其工作原理的片段:
FactoryGirl.define do
  factory :user do
    sequence(:username) { |n| "foo#{n}" }
    password "foobar"
    email { "#{username}@example.com" }

18
如果你是一名 Rails 开发者却没有使用 Railcasts,那么你做错了。 - coneybeare
但如果你是一个真正的Rails开发者,那么你应该先链接到免费内容,然后再建议付费内容。 - Aleks

7
你需要一个工具来在测试之间清理你的数据库。因为你应该能够使用一个干净的数据库运行每个测试。我正在使用非常著名的gem 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

3
当我将你的代码包含在spec_helper中时,出现了错误 Failure / Error:无法从回溯中找到匹配的行 ActiveRecord :: StatementInvalid:SQLite3 :: SQLException:无法在事务内开始事务:开始事务。 - Mike
你不需要为此再添加一个 gem。 - coneybeare
3
我发现解决SQLite异常的方法是删除 clean_with(:truncation) 并完全改变策略为 DatabaseCleaner.strategy = :truncation - Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接