gem rspec-parameterized
は、RSpecでパラメタライズドテストを書くときに便利です。
https://github.com/tomykaira/rspec-parameterized
最近だと、 table syntaxを使っていない場合は rspec-parameterized-core
を使うことで native extensionへの依存をなくすことがなくせるようです。
- https://github.com/rspec-parameterized/rspec-parameterized-core
- rspec-parameterized v1.0.0をリリースした - くりにっき
そんな中、事前に let
や let!
で定義した変数を rspec-parameterized
の where
の中で上書きしたいことがあったため、できるかどうか試してみたときのメモを残します。
目次
環境
letの値を上書き
let
で定義した名前と、 whereで定義した名前を一致させると、 let
で定義した値を上書きできました。
RSpec.describe Blog, type: :model do describe 'rspec_parameterized' do describe 'override let variables' do let!(:author) { create(:author) } # この値を where で上書きしたい let(:blog_name) { 'MyBlog' } let!(:blog) { create(:blog, :with_author, name: blog_name) } # whereの引数に `blog_name` のシンボルを指定することで上書きできる where(:blog_name, :result) do [ %w[foo foo], %w[bar bar] ] end with_them do context 'override blog name' do # このテストもパスする it 'should equal override name' do expect(blog.name).to eq(result) end end end end end end
let!の値を上書き
let!
も、 let
同様に名前を一致させることで上書きできます。
describe 'override let! variables' do let!(:author) { create(:author) } let!(:blog) { create(:blog, name: 'MyBlog', author: author) } where(:blog, :result) do [ [create(:blog, :with_author, name: 'taro blog'), 'taro blog'], [create(:blog, :with_author, name: 'hanako blog'), 'hanako blog'], ] end with_them do context 'override blog name' do it 'should equal override name' do expect(blog.name).to eq(result) end end end end
なお、 where
の中では、 let!
で定義した別のオブジェクトを参照しようとするとエラーになりました。
# let! 定義したauthorを参照しようとすると、それぞれ以下のエラーになる [create(:blog, author: ref(:author), name: 'jiro blog'), 'jiro blog'], # => ActiveRecord::AssociationTypeMismatch: # Author(#9620) expected, got author which is an instance of RSpec::Parameterized::Core::RefArg(#9720) # [create(:blog, author: lazy{ author }, name: 'jiro blog'), 'jiro blog'], # => ActiveRecord::AssociationTypeMismatch: # Author(#9620) expected, got lazy{ author } which is an instance of RSpec::Parameterized::Core::LazyArg(#9740)
ソースコード
Githubに上げました。
https://github.com/thinkAmi-sandbox/rails_7_0_minimal_app
今回のプルリクはこちら。
https://github.com/thinkAmi-sandbox/rails_7_0_minimal_app/pull/14