如何在整个示例组中使用实例变量,即使它在示例之外? [英] How to use an instance variable throughout an Example Group, even if it is outside a Example?
问题描述
我使用的是 Ruby on Rails 3.2.2 和 rspec-rails-2.8.1.我想在整个示例组中使用一个实例变量(在 before
钩子中初始化),即使它在示例之外.也就是说,我想做以下事情:
I am using Ruby on Rails 3.2.2 and rspec-rails-2.8.1. I would like to use an instance variable (initialized in a before
hook) throughout an Example Group, even if it is outside a Example. That is, I would like to make the following:
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
有可能吗?如果是这样,如何?
Is it possible? If so, how?
注意:我想这样做是因为我试图输出有关将要运行的测试的更多信息,如下所示:
Note: I would like to do that because I am trying to output more information about tests that are going to be run, this way:
# 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
推荐答案
您不需要访问 RSpec 设置、拆卸或测试块之一之外的实例变量.如果您需要修改测试的主题,您可能需要创建一个显式主题,然后使用 before 来访问它:
You shouldn't need to access the instance variables outside of one of the RSpec setup, teardown or test blocks. If you need to modify the subject of the test, you may want to create an explicit subject and then use before to access it:
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
这篇关于如何在整个示例组中使用实例变量,即使它在示例之外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!