【问题标题】:Shoulda and RSpec's before应该和 RSpec 之前
【发布时间】:2013-04-16 14:18:34
【问题描述】:

在测试模型字段的有效性之前,我尝试在主题中设置实例变量。我需要设置这个变量,因为验证是有条件的(它只用于某些类型的用户)。所以我有这样的事情:

  context "as a user" do

    before(:each) do
      subject = Organization.new
      subject.editor = "user"
    end

    it { subject.should validate_presence_of :name }

  end

但它并没有按预期工作:

 Failure/Error: it { subject.should validate_presence_of :description }
 RuntimeError:
   Organization#editor attr is not set

我错过了什么?

【问题讨论】:

    标签: ruby-on-rails testing rspec shoulda matcher


    【解决方案1】:

    subject 在你的 before 块中是一个局部变量。看起来你打算使用an explicit subject

    context "as a user" do
      subject { Organization.new }
    
      before(:each) do
        subject.editor = "user"
      end
    
      # usually, you don't explicitly name the subject in an `it` like this
      it { should validate_presence_of :name }
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多