RSpec + Factory_Girl查看测试

aro*_*ick 3 testing rspec ruby-on-rails-3 factory-bot

再次,似乎停留在一个简单的视图测试.这是代码:

require 'spec_helper'

describe "posts/show.html.erb" do
  setup do
    @post = Factory(:post)
  end

  it "should not render a canonical link rel" do
    get :show, :id => @post.id
    response.should_not have_tag("link[rel=?]", "canonical")
  end
end
Run Code Online (Sandbox Code Playgroud)

当我从控制台进行Factory(:post)时,没有任何问题,可以完美地创建它.但是当我在命令行上运行它时,我得到以下内容:

rspec spec/views/posts/show.html.erb_spec.rb 
F

Failures:

  1) posts/show.html.erb should not render a canonical link rel
     Failure/Error: get :show, :id => @post.id
     RuntimeError:
       Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
     # ./spec/views/posts/show.html.erb_spec.rb:11

Finished in 0.06532 seconds
1 example, 1 failure
Run Code Online (Sandbox Code Playgroud)

我缺少什么想法?

Mik*_*wis 5

你想在每个之前使用:

before(:each) do
    @post = Factory(:post)
end
Run Code Online (Sandbox Code Playgroud)

要么

before do
  @post = Factory(:post)
end
Run Code Online (Sandbox Code Playgroud)

为了速记.

而不是设置块.