使用RSpec的共享示例时,为什么我的局部变量未定义?

时间:2011-11-01 16:24:12

标签: ruby-on-rails testing rspec rspec2

我一直在

friend_or_open_profile_view_spec.rb:14:in 'block in <top (required)>': undefined local variable or method 'another_user' for #<Class:0x007f9d95f16668> (NameError)

我可以通过规范在其他地方使用another_user变量。我错过了什么?

此外,还有更好的方法吗?配置文件将根据用户的状态显示不同的组件。我最终希望将所有这些组件移动到可以根据上下文调用的共享示例中。

require 'spec_helper'

describe "viewing a friend's or an open profile" do

  let(:user)         { Factory(:user) }
  let(:another_user) { Factory(:user) }

  before do
    sign_in user 
    User.stub!(:find).and_return(another_user)
  end

  context "when a profile is marked private" do
    it_behaves_like "a restricted profile", another_user
  end

2 个答案:

答案 0 :(得分:0)

我刚刚发现了include_examples,以便共享示例在当前上下文中运行。这可能是我需要的......

答案 1 :(得分:0)

这将有效:

require 'spec_helper'

describe "viewing a friend's or an open profile" do

  before do
    sign_in user 
    User.stub!(:find).and_return(another_user)
  end

  context "when a profile is marked private" do
    it_behaves_like "a restricted profile" do
      let(:user)         { Factory(:user) }
      let(:another_user) { Factory(:user) }
    end
  end
end