RSpec / Shoulda:“should be_valid”失败,“contact.should be_valid”通过

时间:2012-07-12 14:12:31

标签: ruby-on-rails ruby validation rspec

我有以下规格:

  context "no firstname present" do
    let(:contact) { build :contact, firstname: 'Mickey', lastname: '', companyname: '' }
    it "should be valid" do
      should be_valid # Does not work
      contact.should be_valid # Works
    end
  end

为什么should be_valid失败,但contact.should be_valid通过?在it区块内,should be_valid无论如何都应该访问contact?!谢谢你的澄清。

1 个答案:

答案 0 :(得分:11)

您可以使用subject

context "no firstname present" do
  let(:contact) { build :contact, firstname: 'Mickey', lastname: '', companyname: '' }
  subject { contact }
  it { should be_valid }
end

修改

我刚发现its [link]这是测试subject的属性或发送给它的测试消息的好方法