2

我对 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

和规范/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 规范/控制器/shares_controller_spec.rb
我的测试通过了,但它以某种方式破坏了 Cucumber:

$耙黄瓜:好的
耙中止!
验证失败:电子邮件已被占用

任务:TOP => cucumber:ok => db:test:prepare => db:abort_if_pending_migrations => environment
(通过使用 --trace 运行任务查看完整跟踪)

我究竟做错了什么?提前致谢。

4

1 回答 1

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关联,它会自动执行此操作(请参阅文档)。所以这会做:

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

由于您实际上还没有发布您的黄瓜代码,因此很难准确猜测那里发生了什么,但我建议您首先更改这些内容,看看是否有帮助。如果没有,请提供有关您的黄瓜测试的更多信息,我会尝试提供更多建议。

于 2012-09-11T13:04:24.800 回答