0

我正在使用 Ruby on Rails 3.2.2 和 rspec-rails-2.8.1。我想在before整个示例组中使用实例变量(在挂钩中初始化),即使它在示例之外。也就是说,我想做以下事情:

describe "..." do
  before(:each) do
    @user = User.create(...)
  end

  # Here I would like to use the instance variable but I get the error:
  # "undefined method `firstname' for nil:NilClass (NoMethodError)"
  @user.firstname

  it "..." do
    # Here it works.
    @user.firstname
    ...
  end
end

可能吗?如果是这样,怎么做?


注意:我想这样做是因为我试图以这种方式输出有关将要运行的测试的更多信息:

# file_name.html.erb
...

# General idea
expected_value = ...

it "... #{expected_value}" do
  ...
end

# Usage that i am trying to implement
expected_page_title =
  I18n.translate(
    'page_title_html'
    :user => @user.firstname # Here is the instance variable that is called and that is causing me problems
  )

it "displays the #{expected_page_title} page title" do
  view.content_for(:page_title).should have_content(expected_page_title)
end
4

1 回答 1

1

您不需要访问 RSpec 设置、拆卸或测试块之一之外的实例变量。如果您需要修改测试的主题,您可能需要创建一个明确的主题,然后使用 before 来访问它:

describe "..." do
  subject { User.create(... }

  before(:each) do
    subject.firstname #whatever you plan on doing
  end

  it "..." do
    # Here it works.
    subject.firstname
    ...
  end
end
于 2012-04-06T20:23:04.090 回答