使用FactoryGirl的序列时验证失败

时间:2012-09-11 12:50:31

标签: ruby-on-rails rspec rake factory-bot

我是RSpec和FactoryGirl的新手,并且在使用RSpec工厂时尝试通过我的测试。

我有一个spec / controllers / shares_controller_spec.rb规范,如下所示:


require 'spec_helper'

describe SharesController do
  let(:user) do
    user = FactoryGirl.create(:user)
    user
  end

  let(:share) do
    share = FactoryGirl.create(:share)
    share
  end

  context "standard users" do
    it "cannot remove other person's shares" do
      sign_in(:user, user)
      send('delete', 'destroy', :id => share.id)
      response.should redirect_to shares_path
      flash[:alert].should eql('You must be the author to delete this share.')
    end
  end
end

和spec / factories.rb:


FactoryGirl.define do
  factory :user do
    sequence(:email) {|n| "user-#{n}@qwerty.com"}
    password "password"
    password_confirmation "password"
  end

  factory :share do
    title "Test"
    content "Test"
    user FactoryGirl.create(:user)
  end
end

我跑的时候

rspec spec/controllers/shares_controller_spec.rb
我的测试通过,但它以某种方式打破了黄瓜:

$ rake cucumber:ok
rake aborted!
Validation failed: Email has already been taken

Tasks: TOP => cucumber:ok => db:test:prepare => db:abort_if_pending_migrations => environment
(See full trace by running task with --trace)

我做错了什么? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

在你的代码中,有些事情让我感到奇怪:

let(:user) do
  user = FactoryGirl.create(:user)
  user
end

let(:share) do
  share = FactoryGirl.create(:share)
  share
end

为什么要在此处指定usershare然后将其返回?您所需要的只是:

let(:user) { FactoryGirl.create(:user) }
let(:share) { FactoryGirl.create(:share) }

同样在您的工厂中,您无需告知FactoryGirl创建user关联,它会自动执行此操作(请参阅documentation)。所以这样做:

factory :share do
  title "Test"
  content "Test"
  user
end

由于你还没有真正发布黄瓜代码,很难准确猜出那里发生了什么,但我建议先改变这些东西,看看是否有帮助。如果没有,请提供有关黄瓜测试的更多信息,我会尝试提供更多建议。