0

我尝试练习使用 Rspec 进行一些测试,但我有一个奇怪的行为。当我尝试让无效模型遵循红/绿/重构周期时,Rspec 看不到任何错误。

我想确保发布日期不能提前。

我的模型

class Release < ActiveRecord::Base
  belongs_to :game
  belongs_to :platform
  attr_accessible :date

  validates :date, presence: true
end

我的规格文件

require 'spec_helper'

describe Release do
  before {@release = Release.new(date: Time.new(2001,2,3))}

  it{should respond_to :date}
  it{should respond_to :game}
  it{should respond_to :platform}

  describe "when date is not present" do
    before {@release.date = nil}
    it {should_not be_valid}
  end

  describe "when date is anterior" do
    before {@release.date = Time.now.prev_month}    
    it {should_not be_valid}
  end

end    

我的输出

.....

Finished in 0.04037 seconds
5 examples, 0 failures

任何想法 ?

4

2 回答 2

2

当您编写时,it { should_not be_valid }您似乎认为接收者是@release(rspec 怎么知道?),但默认情况下,隐式对象是described 类的实例:

https://www.relishapp.com/rspec/rspec-core/docs/subject/implicit-receiver

用于subject { some_object }明确的主题或it { @release.should_not be_valid }.

更多关于这个:

http://blog.davidchelimsky.net/2012/05/13/spec-smell-explicit-use-of-subject/

于 2012-12-06T22:28:01.277 回答
1

尝试:

it { @release.should_not be_valid}

反而。

于 2012-12-06T21:21:12.453 回答