Reputation: 1026
I'm trying to DRY my spec using RSpec's Macros, and I encountered a problem.
describe "..." do
let!(:blog) { create(:blog) }
post "/blogs/#{blog.id}/posts" do
# some macros
end
end
I want to get access to blog
variable but I don't want to do it inside it { ... }
block so would be able to use my macros regardless of the resource (e.g. I want to apply it to blogs
, posts
, comments
, etc).
Is it possible?
Upvotes: 1
Views: 257
Reputation: 22707
I want to get access to blog variable but I don't want to do it inside it { ... } block
Try not to think of let
as normally-scoped variable definition. let
is a complex helper method for caching the result of a code block across multiple calls within the same example group. Anything you let
will only exist within example groups, meaning you can't access a let
ted "variable" outside it
blocks.
require 'spec'
describe "foo" do
let(:bar) { 1 }
bar
end
# => undefined local variable or method `bar'
That said, if you just want to reuse the result of create(:blog)
across multiple examples, you can do:
describe "foo" do
let(:blog) { create(:blog) }
it "does something in one context" do
post "/blogs/#{blog.id}/posts"
# specification
end
it "does something else in another context" do
post "/blogs/#{blog.id}/comments"
# specification
end
end
Upvotes: 3