【问题标题】:Why is my local variable undefined when using RSpec's shared examples?为什么使用 RSpec 的共享示例时我的局部变量未定义?
【发布时间】:2011-11-01 16:24:12
【问题描述】:

我一直在努力

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

【问题讨论】:

  • 你能展示你分享的例子吗?如果你写it_behaves_like "a restricted profile", Factory(:user),它会起作用吗?

标签: ruby-on-rails testing rspec rspec2


【解决方案1】:

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

【讨论】:

  • include_examples 只是it_behaves_like_a 的别名
【解决方案2】:

这将起作用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多