0

undefinded local variable or method user在这个测试中得到了一个。有人帮忙吗?

context "[user IS signed in]" do     
  before do
      user = Fabricate(:user)
      league = Fabricate(:league)
      event = Fabricate(:event, league: league)
      @request.env["devise.mapping"] = Devise.mappings[:user]
      sign_in user
      ApplicationController.any_instance.stub(:primary_leagues).and_return([league])
  end

  it "[creates a pick for a user]" do
    post 'create', {:pick => {user_id: user.id, event_id: event.id, league_id: league.id, points_pick: "home"}}
    Pick.all.size.should eq(1)
  end
4

1 回答 1

2

您的before块声明user为局部变量,因此它超出了您的it块的范围。

解决此问题的最简单方法是在before块中声明成员变量,例如

before do
  @user = Fabricate(:user)
  @league = Fabricate(:league)
  @event = Fabricate(:event, league: @league)
  ...
end

it "[creates a pick for a user]" do
  post 'create', {:pick => {user_id: @user.id, event_id: @event.id, league_id: @league.id, points_pick: "home"}}
  Pick.all.size.should eq(1)
end

这是有效的,因为before并且it正在相同(生成的)类实例的上下文中执行。

或者,您可以声明您的变量let并保留代码示例,例如

context "[user IS signed in]" do     
  let(:user) { Fabricate(:user) }
  let(:league) { Fabricate(:league) }
  let(:event) { Fabricate(:event, league: league) }

  before do
    @request.env["devise.mapping"] = Devise.mappings[:user]
    sign_in user
    ApplicationController.any_instance.stub(:primary_leagues).and_return([league])
  end

  it "[creates a pick for a user]" do
    post 'create', {:pick => {user_id: user.id, event_id: event.id, league_id: league.id, points_pick: "home"}}
    Pick.all.size.should eq(1)
  end

let将在第一次引用时实例化给定变量并记住结果。

于 2013-09-26T12:54:59.370 回答