【问题标题】:Rspec: let versus let with an exclamation markRspec:let 与 let 带感叹号
【发布时间】:2013-10-25 16:37:19
【问题描述】:

谁能给我解释一下为什么必须使用let!而不是在这种情况下让?仅当我包含 ! 时测试才通过。我以为我明白 let 会在该块中的每个“it”语句之前自动执行,但显然情况并非如此。

describe Artist do

  before do
  @artist = Artist.new(name: "Example User", email: "user@example.com",
                 password: "foobar", password_confirmation: "foobar")
  end
  subject { @artist }

  describe "virtual requests" do
    let!(:virtual1) { FactoryGirl.create(:virtual_request, artist: @artist ) }
    let!(:virtual2) { FactoryGirl.create(:virtual_request, artist: @artist ) }

    it "should be multiple" do
      @artist.virtual_requests.count.should == 2 
    end
  end
end

【问题讨论】:

  • 在这里找到了很好的解释stackoverflow.com/questions/17407733/…
  • 为什么let中没有艺术家?
  • 我不得不在规范中的某个时候使用 .dup 方法,不能使用 let 变量,所以我将它切换到一个实例。

标签: ruby-on-rails rspec ruby-on-rails-4 capybara


【解决方案1】:

因为let 是懒惰的。如果你不调用它,它不会做任何事情。

相反,let! 处于活动状态,并会在您经过时执行其块内的代码。

在您的代码中,如果您将let! 替换为let,您的测试将不会通过。

原因是你之后没有调用:virtual1:virtual2,所以块里面的代码不会被执行,FactoryGirl也不会创建记录。

【讨论】:

  • 通常,如果你发现你正在使用let!,你真的应该使用before。如果你总是需要执行代码,它属于before。另请注意,您实际上从未使用过 let 变量,因此它们甚至不需要名称。
猜你喜欢
  • 2013-09-21
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 2012-03-06
  • 2011-09-15
  • 2018-02-08
  • 2012-07-07
  • 1970-01-01
相关资源
最近更新 更多