contest_entry_spec.rb

    require 'spec_helper'

    describe ContestEntry do

      before(:all) do
        @admission=Factory(:project_admission)
        @project=Factory(:project_started, :project_type => @admission.project_type)
        @creative=Factory(:approved_creative, :creative_category => @admission.creative_category)
        @contest_entry=Factory(:contest_entry, :design_file_name => 'bla bla bla', :owner => @creative, :project => @project)
      end

      context 'non-specific tests' do
        subject { @contest_entry }
        it { should belong_to(:owner).class_name('User') }
        it { should belong_to(:project) }
        it { should have_many(:entry_comments) }

        it { should validate_presence_of(:owner) }
        it { should validate_presence_of(:project) }
        it { should validate_presence_of(:entry_no) }
        it { should validate_presence_of(:title) }

      end
end

当我运行这些测试时,一切正常,但如果我将before(:all)更改为before(:each),每个测试都将失败.我不知道为什么会这样?

这就是错误所在

 Failure/Error: @contest_entry=Factory(:contest_entry, :design_file_name => 'bla bla bla', :owner => @creative, :project => @project)
     ActiveRecord::RecordInvalid:
       Validation Failed: User is not allowed for this type of project

推荐答案

before(:all)在运行所有示例之前运行一次块.

before(:each)在文件中的每个规格之前运行一次块

before(:all)在所有it个块运行之前设置实例变量@admission, @project, @creative, @contest_entry一次.

但是,每次运行it块时,:before(:each)都会重置before块中的实例变量.

这是一个微妙的区别,但很重要

再一次

before(:all)
#before block is run
it { should belong_to(:owner).class_name('User') }
it { should belong_to(:project) }
it { should have_many(:entry_comments) }

it { should validate_presence_of(:owner) }
it { should validate_presence_of(:project) }
it { should validate_presence_of(:entry_no) }
it { should validate_presence_of(:title) }

before(:each)
# before block
it { should belong_to(:owner).class_name('User') }
# before block
it { should belong_to(:project) }
# before block
it { should have_many(:entry_comments) }
# before block

# before block
it { should validate_presence_of(:owner) }
# before block
it { should validate_presence_of(:project) }
# before block
it { should validate_presence_of(:entry_no) }
# before block
it { should validate_presence_of(:title) }

Ruby-on-rails相关问答推荐

HTTP:MimeNegotiation::InvalidType(html不是有效的MIME类型):""

Rails 7.1.3如何在生产环境中查看堆栈跟踪

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

为什么有时会出现类型错误没有将 StringIO 隐式转换为 String?Ruby /导轨

正确更新其他列的更新列

Rails 4 中的 null_session 和 reset_session 有什么区别?

rails select标签,预先 Select 了多个值

Rails:如何访问 RESTful 助手?

从 Authlogic 迁移到 Devise

rails:防止闪烁消息显示两次

如何在生产中部署 resque worker?

什么是 Ruby 中的 Python 文档字符串?

如何按值按降序对哈希进行排序并在 ruby​​ 中输出哈希?

删除链接在 Rails 3 视图中发送Get而不是Delete

Rails 3.1 中的 Rails.cache 错误 - TypeError: can't dump hash with default proc

为什么 Google Oauth 在我的 Rails 应用程序中返回无效的 redirect_urI?

Vagrant上的Rails 4.2服务器端口转发不起作用

ActiveModel::MissingAttributeError:无法使用 FactoryGirl 写入未知属性ad_id

Ruby 中有与 slice 函数相反的函数吗?

将数组传递到 hidden_​​field ROR