Reputation: 18881
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
Upvotes: 0
Views: 298
Reputation: 51717
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
Upvotes: 1