rspec_test_data 1.0.0.pre1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a910ceb350cd1c0038d9ed55855a3cf61518eff07edff511b97d82c8a7b41df3
4
+ data.tar.gz: 852ac12267d03e947fa86a1672814b9e7da9b00897344cf00973d800281b8932
5
+ SHA512:
6
+ metadata.gz: 7ffcbf8472b3b97f5adbfc59af4364f3160c9a5ce65f3b9283e84c5a2bd8bfa58606b5e25e03077b2072d464374bda176ed6602427fa4b7f002df55d3671d0df
7
+ data.tar.gz: 6bed65c1cb5b4e22afc3730bfb1837031eb5f90dcc58477edb90f892db43f8791215d225eca94ff1bb71a69e0d6175858f9851719db40aee2483ab8ff509818c
@@ -0,0 +1,35 @@
1
+ version: 2.1
2
+ orbs:
3
+ # See https://circleci.com/developer/orbs/orb/circleci/ruby
4
+ ruby: circleci/ruby@1.2.0
5
+ jobs: # keyword
6
+ test: # my name for the job
7
+ parameters: # keyword
8
+ ruby-version: # my parameter name
9
+ type: string # type is a keyword
10
+ docker: # keyword
11
+ - image: cimg/base:stable
12
+ steps: # keyword
13
+ - checkout # magic name
14
+ - ruby/install: # ruby/ is from the orb name, install is a command in that orb
15
+ version: << parameters.ruby-version >> # magic nonsense for param subst
16
+ - run:
17
+ command: "bin/setup"
18
+ - run:
19
+ name: "Create the test results directory because you can't just store_test_results with a file and if you do you do not get any sort of error because wtf is with this platform?"
20
+ command: mkdir -p /tmp/test-results
21
+ - run:
22
+ command: bin/ci /tmp/test-results/rspec_results.xml
23
+ - store_test_results: # store_test_results is magic from circle
24
+ path: /tmp/test-results # path is a param to store_test_results and it must be a directory not a file
25
+ - store_artifacts: # store_artifacts is magic from circle
26
+ path: /tmp/test-results # path is the param to store_artifacts
27
+ workflows: # keyword
28
+ all-rubies: # my name for the workflow
29
+ jobs: # keyword
30
+ - test: # my name for the job
31
+ matrix: # keyword
32
+ parameters: # keyword
33
+ # All rubies being maintained per this page:
34
+ # https://www.ruby-lang.org/en/downloads/branches/
35
+ ruby-version: [ "2.5", "2.6", "2.7", "3.0" ]
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1 @@
1
+ --require spec_helper
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at davetron5000 (at) gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,5 @@
1
+ # Contributing
2
+
3
+ * Code changes for style, cleanliness, eleganance, or other aesthetic stuff will not be accepted.
4
+ * All proposed changes must have a clear problem statement and be based on a real-world scenario. Imagined problems will not be solved.
5
+ * Tests are appreciated with all pull requests, but I realize there aren't any in here so help with how this might be tested would be very much appreciated.
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in with_clues.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
data/LICENSE.md ADDED
@@ -0,0 +1,33 @@
1
+ [rspec_test_data] Copyright (2021) (David Copeland)(“Licensor”)
2
+
3
+ Hippocratic License Version Number: 2.1.
4
+
5
+ Purpose. The purpose of this License is for the Licensor named above to permit the Licensee (as defined below) broad permission, if consistent with Human Rights Laws and Human Rights Principles (as each is defined below), to use and work with the Software (as defined below) within the full scope of Licensor’s copyright and patent rights, if any, in the Software, while ensuring attribution and protecting the Licensor from liability.
6
+
7
+ Permission and Conditions. The Licensor grants permission by this license (“License”), free of charge, to the extent of Licensor’s rights under applicable copyright and patent law, to any person or entity (the “Licensee”) obtaining a copy of this software and associated documentation files (the “Software”), to do everything with the Software that would otherwise infringe (i) the Licensor’s copyright in the Software or (ii) any patent claims to the Software that the Licensor can license or becomes able to license, subject to all of the following terms and conditions:
8
+
9
+ * Acceptance. This License is automatically offered to every person and entity subject to its terms and conditions. Licensee accepts this License and agrees to its terms and conditions by taking any action with the Software that, absent this License, would infringe any intellectual property right held by Licensor.
10
+
11
+ * Notice. Licensee must ensure that everyone who gets a copy of any part of this Software from Licensee, with or without changes, also receives the License and the above copyright notice (and if included by the Licensor, patent, trademark and attribution notice). Licensee must cause any modified versions of the Software to carry prominent notices stating that Licensee changed the Software. For clarity, although Licensee is free to create modifications of the Software and distribute only the modified portion created by Licensee with additional or different terms, the portion of the Software not modified must be distributed pursuant to this License. If anyone notifies Licensee in writing that Licensee has not complied with this Notice section, Licensee can keep this License by taking all practical steps to comply within 30 days after the notice. If Licensee does not do so, Licensee’s License (and all rights licensed hereunder) shall end immediately.
12
+
13
+ * Compliance with Human Rights Principles and Human Rights Laws.
14
+
15
+ 1. Human Rights Principles.
16
+
17
+ (a) Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights and the United Nations Global Compact that define recognized principles of international human rights (the “Human Rights Principles”). Licensee shall use the Software in a manner consistent with Human Rights Principles.
18
+
19
+ (b) Unless the Licensor and Licensee agree otherwise, any dispute, controversy, or claim arising out of or relating to (i) Section 1(a) regarding Human Rights Principles, including the breach of Section 1(a), termination of this License for breach of the Human Rights Principles, or invalidity of Section 1(a) or (ii) a determination of whether any Law is consistent or in conflict with Human Rights Principles pursuant to Section 2, below, shall be settled by arbitration in accordance with the Hague Rules on Business and Human Rights Arbitration (the “Rules”); provided, however, that Licensee may elect not to participate in such arbitration, in which event this License (and all rights licensed hereunder) shall end immediately. The number of arbitrators shall be one unless the Rules require otherwise.
20
+
21
+ Unless both the Licensor and Licensee agree to the contrary: (1) All documents and information concerning the arbitration shall be public and may be disclosed by any party; (2) The repository referred to under Article 43 of the Rules shall make available to the public in a timely manner all documents concerning the arbitration which are communicated to it, including all submissions of the parties, all evidence admitted into the record of the proceedings, all transcripts or other recordings of hearings and all orders, decisions and awards of the arbitral tribunal, subject only to the arbitral tribunal's powers to take such measures as may be necessary to safeguard the integrity of the arbitral process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3) Article 26(6) of the Rules shall not apply.
22
+
23
+ 2. Human Rights Laws. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any Human Rights Laws. “Human Rights Laws” means any applicable laws, regulations, or rules (collectively, “Laws”) that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights; provided, however, that such Laws are consistent and not in conflict with Human Rights Principles (a dispute over the consistency or a conflict between Laws and Human Rights Principles shall be determined by arbitration as stated above). Where the Human Rights Laws of more than one jurisdiction are applicable or in conflict with respect to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
24
+
25
+ 3. Indemnity. Licensee shall hold harmless and indemnify Licensor (and any other contributor) against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor’s reasonable attorneys’ fees, arising out of or relating to Licensee’s use of the Software in violation of Human Rights Laws or Human Rights Principles.
26
+
27
+ * Failure to Comply. Any failure of Licensee to act according to the terms and conditions of this License is both a breach of the License and an infringement of the intellectual property rights of the Licensor (subject to exceptions under Laws, e.g., fair use). In the event of a breach or infringement, the terms and conditions of this License may be enforced by Licensor under the Laws of any jurisdiction to which Licensee is subject. Licensee also agrees that the Licensor may enforce the terms and conditions of this License against Licensee through specific performance (or similar remedy under Laws) to the extent permitted by Laws. For clarity, except in the event of a breach of this License, infringement, or as otherwise stated in this License, Licensor may not terminate this License with Licensee.
28
+
29
+ * Enforceability and Interpretation. If any term or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction; provided, however, subject to a court modification pursuant to the immediately following sentence, if any term or provision of this License pertaining to Human Rights Laws or Human Rights Principles is deemed invalid, illegal, or unenforceable against Licensee by a court of competent jurisdiction, all rights in the Software granted to Licensee shall be deemed null and void as between Licensor and Licensee. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by Laws, the court may modify this License to affect the original purpose that the Software be used in compliance with Human Rights Principles and Human Rights Laws as closely as possible. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
30
+
31
+ * Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES “AS IS,” WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM.
32
+
33
+ This Hippocratic License is an Ethical Source license (https://ethicalsource.dev) and is offered for use by licensors and licensees at their own risk, on an “AS IS” basis, and with no warranties express or implied, to the maximum extent permitted by Laws.
data/README.md ADDED
@@ -0,0 +1,387 @@
1
+ # rspec\_test\_data - Create Complex test data with the ability to share with other tests or seed data
2
+
3
+ [![<sustainable-rails>](https://circleci.com/gh/sustainable-rails/rubygem.svg?style=shield)](https://app.circleci.com/pipelines/github/sustainable-rails/rubygem)
4
+
5
+ ## Install
6
+
7
+ ```ruby
8
+ # In your Gemfile
9
+ gem "rspec_test_data"
10
+ ```
11
+
12
+ *Note*: Nothing is required when you do this. You *must* configure things. See below.
13
+
14
+ ## What Problem Does This Solve?
15
+
16
+ This allows the creation of test data that is more than one factory, but scoped to a test file.
17
+
18
+ Rails comes with the concept of *fixtures* which is a global set of data that is available to all of your tests. Many developers, myself
19
+ included, find this is hard to manage when an app becomes non-trivial, and can get extremely complicated when you use and validate
20
+ foreign key constraints.
21
+
22
+ [FactoryBot](https://github.com/thoughtbot/factory_bot) provides an alternative, which are *factories* to create instances of objects you
23
+ would use as input to a test. These work great for creating single objects. They do not work as great when you need to create a lot of
24
+ objects.
25
+
26
+ *Why would you need to create a lot of objects?* Glad you asked. A very common reason in my experience is if you are writing some code
27
+ that needs to perform a query that is complex. For example, show me all the customers who have said they have insurance, but who have
28
+ not provided the details of their insurance, but filter out everyone that has not scheduled an appointment.
29
+
30
+ Testing this requires creating several records in all the various states to check your query logic, then running the query and figuring
31
+ out what came back.
32
+
33
+ *OK, so use factories* - for a single test, it *is* better to just use factories to create a bunch of stuff. But, when you start needing
34
+ to create them in more than one test, or want to have that data in your seed data for local development, RSpec provides very rudimentary
35
+ tools for this. Since RSpec uses an internal DSL via `let` and `shared_context` and friends, it is hard to manage, compose, and re-use
36
+ this stuff.
37
+
38
+ But! We have *Object-Oriented Programming*! If we could put this stuff in a class, we can use that class, make that class configurable
39
+ (or not), extend that class, etc. We can use the tools we use every day to manage our complex test data.
40
+
41
+ *OK, so why do I need a gem?* This gem facilitates that by providing an implicit `test_data` object that allows access to a test data
42
+ class you define.
43
+
44
+ ## Using This Gem
45
+
46
+ Suppose you have `spec/services/appointments_spec.rb`:
47
+
48
+ ```ruby
49
+ RSpec.describe Appointments do
50
+ describe "#upcoming" do
51
+ context "no restriction by service" do
52
+ it "returns all in the future" do
53
+ a1 = create(:appointment, date: 4.days.from_now)
54
+ a2 = create(:appointment, date: 14.days.from_now)
55
+ canceled = create(:appointment, :canceled, date: 3.days.from_now)
56
+ past = create(:appointment, date: 3.days.ago)
57
+
58
+ upcoming = appointments.upcoming
59
+
60
+ expect(upcoming.size).to eq(2)
61
+ aggregate_failures do
62
+ expect(upcoming).to include(a1)
63
+ expect(upcoming).to include(a2)
64
+ end
65
+ end
66
+ end
67
+ context "restrict by service" do
68
+ it "returns those in the future for the given service" do
69
+ s1 = create(:service)
70
+ s2 = create(:service)
71
+
72
+ a1 = create(:appointment, service: s1, date: 4.days.from_now)
73
+ a2 = create(:appointment, service: s2, date: 14.days.from_now)
74
+ canceled = create(:appointment, :canceled, service: s1, date: 3.days.from_now)
75
+ past = create(:appointment, service: s1, date: 3.days.ago)
76
+
77
+ upcoming = appointments.upcoming(service: s1)
78
+
79
+ expect(upcoming.size).to eq(1)
80
+ expect(upcoming).to include(a1)
81
+ end
82
+ end
83
+ end
84
+ end
85
+ ```
86
+
87
+ The test set up for both tests is pretty similar. The first test does not specify the service, but the service doesn't matter to that test, so it could absolutely use the exact same set of services and appointments that the second test uses.
88
+
89
+ It also might be nice to use this setup when you are working on the front-end to have some realistic data or as part of a larger set of
90
+ test data for a system test that involves this code.
91
+
92
+ We could put that in a `before` block or a series of `let` calls, but this doesn't make it easy to use outside this test. Enter
93
+ `rspec_test_data`.
94
+
95
+ Assuming you have configured this gem, you would create the class `RspecTestData::Services::Appointments` in the file
96
+ `spec/services/appointments.test_data.rb` like so:
97
+
98
+ ```ruby
99
+ module RspecTestData::Services
100
+ class Appointments < RspecTestData::BaseTestData
101
+
102
+ attr_reader :service, :upcoming_appointment_service, :upcoming_appointment_other_service
103
+
104
+ def initialize
105
+ @service = create(:service)
106
+ other_service = create(:service)
107
+
108
+ @upcoming_appointment_service = create(:appointment,
109
+ service: s1,
110
+ date: 4.days.from_now)
111
+ @upcoming_appointment_other_service = create(:appointment,
112
+ service: s2,
113
+ date: 14.days.from_now)
114
+ canceled = create(:appointment, :canceled,
115
+ service: s1,
116
+ date: 3.days.from_now)
117
+ past = create(:appointment,
118
+ service: s1,
119
+ date: 3.days.ago)
120
+ end
121
+ end
122
+ end
123
+ ```
124
+
125
+ This class creates the test data and exposes only the data the test is going to need. Now, the test looks like so:
126
+
127
+ ```ruby
128
+ RSpec.describe Appointments do
129
+ describe "#upcoming" do
130
+ context "no restriction by service" do
131
+ it "returns all in the future" do
132
+ upcoming = appointments.upcoming
133
+
134
+ expect(upcoming.size).to eq(2)
135
+
136
+ aggregate_failures do
137
+ expect(upcoming).to include(test_data.upcoming_appointment_service)
138
+ expect(upcoming).to include(test_data.upcoming_appointment_other_service)
139
+ end
140
+ end
141
+ end
142
+ context "restrict by service" do
143
+ it "returns those in the future for the given service" do
144
+ upcoming = appointments.upcoming(service: test_data.service)
145
+
146
+ expect(upcoming.size).to eq(1)
147
+ expect(upcoming).to include(test_data.upcoming_appointment_service)
148
+ end
149
+ end
150
+ end
151
+ end
152
+ ```
153
+
154
+ Whoa. Yes, the setup is gone and subsumed into the test data class. This is a trade-off. You make this trade-off in this case because
155
+ you want access to the test data outside this class. You can achieve this like so, in your `db/seeds.rb`:
156
+
157
+ ```ruby
158
+ require "rspec_test_data/seeds_helper"
159
+
160
+ test_data_seeds_helper = RspecTestData::SeedsHelper.for_rails
161
+ test_data = test_data_seeds_helper.load("RspecTestData::Services::Appointments")
162
+
163
+ puts test_data.upcoming_appointment_service.customer.name +
164
+ " has an upcoming appointment with the service"
165
+ ```
166
+
167
+ This can be extremely helpful for aligning your dev environment, where you may want realistic data to work on the UI, with your tests.
168
+
169
+ Note that since the test data class is just a class, it can accept arguments to the constructor that affect the behavior. Perhaps you
170
+ want your seed data to be a bit more realistic:
171
+
172
+ ```ruby
173
+ require "rspec_test_data/seeds_helper"
174
+
175
+ test_data_seeds_helper = RspecTestData::SeedsHelper.for_rails
176
+ test_data = test_data_seeds_helper.load("RspecTestData::Services::Appointments",
177
+ service_name: "Physical Therapy")
178
+
179
+ puts test_data.upcoming_appointment_service.customer.name +
180
+ " has an upcoming appointment for Physical Therapy"
181
+ ```
182
+
183
+ The test data class accommodates this using plain ole Ruby:
184
+
185
+ ```ruby
186
+ module RspecTestData::Services
187
+ class Appointments < RspecTestData::BaseTestData
188
+
189
+ attr_reader :service, :upcoming_appointment_service, :upcoming_appointment_other_service
190
+
191
+ def initialize(service_name: :use_factory)
192
+ @service = if service_name == :use_factory
193
+ create(:service)
194
+ else
195
+ create(:service, name: service_name)
196
+ end
197
+ other_service = create(:service)
198
+
199
+ # ... as before
200
+
201
+ end
202
+ end
203
+ end
204
+ ```
205
+
206
+ This class then becomes a sort of "super factory" you can use to create complex test data. Suppose you want to search for upcoming
207
+ appointments by service name? You'll need to make sure both services are created with distinct names so you can reliably search by name
208
+
209
+ ```ruby
210
+ module RspecTestData::Services
211
+ class Appointments < RspecTestData::BaseTestData
212
+
213
+ attr_reader :service, :upcoming_appointment_service, :upcoming_appointment_other_service
214
+
215
+ def initialize(service_name: :use_factory,
216
+ other_service_name: :use_factory)
217
+
218
+ @service = if service_name == :use_factory
219
+ create(:service)
220
+ else
221
+ create(:service, name: service_name)
222
+ end
223
+ other_service = if other_service_name == :use_factory
224
+ create(:service)
225
+ else
226
+ create(:service, name: other_service_name)
227
+ end
228
+
229
+ # ... as before
230
+
231
+ end
232
+ end
233
+ end
234
+ ```
235
+
236
+ Now, in your test you can override the default creation of the test data per test. If you declare a `let` variable named
237
+ `test_data_override`, *that* will be set to `test_data`. To create this, you have access to the class via the implicitly defined
238
+ variable `test_data_class`.
239
+
240
+ ```ruby
241
+ RSpec.describe Appointments do
242
+ describe "#upcoming" do
243
+ context "no restriction by service" do
244
+ it "returns all in the future" # as before
245
+ end
246
+ context "restrict by service" do
247
+ it "returns those in the future for the given service" # as before
248
+ end
249
+ context "restrict by service name partial match" do
250
+ let(:test_data_override) {
251
+ test_data_class.new(service_name: "Physical Therapy",
252
+ other_service_name: "Ortho Exam")
253
+ }
254
+ it "returns those in the future for the given service" do
255
+ upcoming = appointments.upcoming(service_name: "phys")
256
+
257
+ expect(upcoming.size).to eq(1)
258
+ expect(upcoming).to include(test_data.upcoming_appointment_service)
259
+ end
260
+ end
261
+ end
262
+ end
263
+ ```
264
+
265
+ Notice how the *only* magic happening is the definition of `test_data` and `test_data_class` based on a convention of a class defined
266
+ in a file with a specific name. The test data class is just a normal Ruby class. Your test that overrides it just uses
267
+ Ruby.
268
+
269
+ You can opt out using RSpec metadata:
270
+
271
+ ```ruby
272
+ RSpec.describe Appointments do
273
+ describe "#upcoming" do
274
+ context "no restriction by service" do
275
+ it "returns all in the future" # as before
276
+ end
277
+ context "restrict by service" do
278
+ it "returns those in the future for the given service" # as before
279
+ end
280
+ context "restrict by service name partial match", test_data: false do
281
+ it "returns those in the future for the given service" do
282
+ # test_data is not defined here - do whatever you want
283
+ end
284
+ end
285
+ end
286
+ end
287
+ ```
288
+
289
+ Test Data can also be useful for system tests. Perhaps you want a system test of the appointment search feature.
290
+
291
+ ```ruby
292
+ # spec/system/appointments/search_spec.rb
293
+ RSpec.describe "searching for appointments" do
294
+ scenario "show all appointments" do
295
+ login_as test_data.therapist
296
+
297
+ click_on "Search Appointments"
298
+ click_on "View All"
299
+
300
+ expect(page).to have_content(test_data.upcoming_appointment_service.description)
301
+ expect(page).to have_content(test_data.upcoming_appointment_other_service.description)
302
+ expect(page).not_to have_content(test_data.canceled_appointment.description)
303
+ end
304
+ end
305
+ ```
306
+
307
+ To make this work, you'll need to define `RspecTestData::System::Appointments::Search` in the file
308
+ `spec/system/appointments/search.test_data.rb`.
309
+
310
+ To re-use the test data for the `Appointments` class, all you have to do is use a plain old Ruby concept: inheritance:
311
+
312
+ ```ruby
313
+ require_relative "../services/appointments.test_data.rb"
314
+ class RspecTestData::System::Appointments::Search < RspecTestData::Services::Appointments
315
+ attr_reader :therapist, :canceled_appointment
316
+ def initialize(...)
317
+ super(...)
318
+
319
+ @therapist = create(:user, type: :therapist)
320
+
321
+ @canceled_appointment = create(:appointment, :canceled,
322
+ service: @service,
323
+ date: 10.days.from_now)
324
+ end
325
+ end
326
+ ```
327
+
328
+ This gem isn't really facilitating this re-use - we can do it because this is just a class and Ruby allows it. No new skills or DSL is
329
+ needed here. You can do whatever makes sense.
330
+
331
+ ## Configuration & Setup
332
+
333
+ In your `spec/spec_helper.rb`:
334
+
335
+ ```ruby
336
+ require "rspec_test_data/rspec_setup" # brings in the setup below
337
+ require "rspec_test_data/base_test_data" # Avoid having to require this in all test data class files
338
+
339
+ RSpec.configure do |config|
340
+
341
+ # whatever set up you have already
342
+
343
+ config.before(:example) do |example|
344
+ RspecTestData::Setup.new(example)
345
+ end
346
+ end
347
+ ```
348
+
349
+ Even here, the setup is explicit so you know it's happening. Nothing is done to you automatically.
350
+
351
+ If you don't create an analogous `.test_data.rb` file, nothing happens, your test works like normal.
352
+
353
+ ## Debugging
354
+
355
+ Often, libraries with implicit behavior are hard to debug when nothing happens. The library can't tell that you meant to do something
356
+ but failed - it just thinks you didn't try to do something. To help debug those situations:
357
+
358
+ ```
359
+ DEBUG_TEST_DATA=true bin/rspec spec/services/appointments_spec.rb
360
+ ```
361
+
362
+ This will cause rspec\_test\_data to output verbose information about what it's doing, what it tried, what worked, what didn't. You can also add the `debug_test_data: true`
363
+ metadata to any test or spec to trigger the same behavior.
364
+
365
+ ## A Note on Implementation
366
+
367
+ I have been using this for several months in two Rails apps that I would say are "medium-small". It is working great for me, but if you
368
+ look at the code for `RspecTestData::Setup`, there is a bit of wizardry in there. Be careful with how you use this.
369
+
370
+ ## Ejecting from the Magic
371
+
372
+ Since your test data class is just a class, you can eject from all of this like so:
373
+
374
+ 1. Remove this Gem
375
+ 2. Keep a copy of `RspecTestData::BaseTestData` in your app, e.g. in `lib/rspec_test_data/base_test_data.rb`
376
+ 3. In your RSpec tests, add this:
377
+
378
+ ```ruby
379
+ require_relative "./appointments.test_data.rb"
380
+
381
+ # Then, in a test...
382
+ let(:test_data) { RspecTestData::Services::Appointments.new }
383
+ ```
384
+
385
+ ## Contributing
386
+
387
+ Would love feedback on the implementation and how it might be unit tested.
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
data/bin/ci ADDED
@@ -0,0 +1,10 @@
1
+ #!/bin/bash
2
+
3
+ set -e
4
+ echo "[bin/ci] Running tests"
5
+ if [ -z $1 ]; then
6
+ bin/rspec --format=doc
7
+ else
8
+ echo "[bin/ci] Generating JUnit XML output to $1"
9
+ bin/rspec --format RspecJunitFormatter --out $1 --format=doc
10
+ fi
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "with_clues"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/rspec ADDED
@@ -0,0 +1,29 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ #
5
+ # This file was generated by Bundler.
6
+ #
7
+ # The application 'rspec' is installed as part of a gem, and
8
+ # this file is here to facilitate running it.
9
+ #
10
+
11
+ require "pathname"
12
+ ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
13
+ Pathname.new(__FILE__).realpath)
14
+
15
+ bundle_binstub = File.expand_path("../bundle", __FILE__)
16
+
17
+ if File.file?(bundle_binstub)
18
+ if File.read(bundle_binstub, 300) =~ /This file was generated by Bundler/
19
+ load(bundle_binstub)
20
+ else
21
+ abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run.
22
+ Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.")
23
+ end
24
+ end
25
+
26
+ require "rubygems"
27
+ require "bundler/setup"
28
+
29
+ load Gem.bin_path("rspec-core", "rspec")
data/bin/setup ADDED
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle check || bundle install
@@ -0,0 +1,6 @@
1
+ require "factory_bot"
2
+ module RspecTestData
3
+ class BaseTestData
4
+ include FactoryBot::Syntax::Methods
5
+ end
6
+ end
@@ -0,0 +1,52 @@
1
+ module RspecTestData
2
+ class Setup
3
+ def initialize(example)
4
+ debug = ->(*) {}
5
+
6
+ if example.metadata[:debug_test_data] || ENV["DEBUG_TEST_DATA"] == "true"
7
+ debug = ->(*args) {
8
+ first_message,rest = args[0], args[1..-1]
9
+ puts *([ "[ debug_test_data ] #{args[0]}" ] + args[1..-1])
10
+ }
11
+ end
12
+
13
+ use_test_data = example.metadata[:test_data].nil? || example.metadata[:test_data] == true
14
+ if !use_test_data
15
+ debug.("Spec opted out of test_data (#{example.description})")
16
+ return
17
+ end
18
+
19
+ test_data_file = example.file_path.gsub(/_spec\.rb$/,".test_data.rb")
20
+
21
+ if !File.exists?(test_data_file)
22
+ debug.("Can't find #{test_data_file}, so assuming none to load")
23
+ return
24
+ end
25
+
26
+ require test_data_file
27
+
28
+ test_data_class_name = "RspecTestData::" + example.file_path.gsub(/^.\/spec\//,"").gsub(/_spec\.rb$/,"").classify
29
+ test_data_class = begin
30
+ debug.("Loading '#{test_data_class_name}' as the test data class name")
31
+ test_data_class_name.constantize
32
+ rescue NameError => ex
33
+ raise "Expected '#{test_data_file}' to define '#{test_data_class_name}', but it does not: #{ex.message}"
34
+ end
35
+
36
+ example.example_group.let(:test_data_class) { test_data_class }
37
+
38
+ if example.example_group.method_defined?(:test_data_override)
39
+ debug.("test_data_override for '#{example.description}'")
40
+ example.example_group.let(:test_data) { test_data_override }
41
+ else
42
+ if example.metadata[:test_data_eager] == true
43
+ test_data = test_data_class.new
44
+ example.example_group.let(:test_data) { test_data }
45
+ else
46
+ example.example_group.let(:test_data) { test_data_class.new }
47
+ end
48
+ end
49
+
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,31 @@
1
+ require "pathname"
2
+ require_relative "./base_test_data"
3
+
4
+ module RspecTestData
5
+ class SeedsHelper
6
+
7
+ def self.for_rails
8
+ self.new(Rails.root / "spec")
9
+ end
10
+
11
+ def initialize(spec_path)
12
+ @spec_path = spec_path
13
+ end
14
+
15
+ def load(test_data_class_name,**args)
16
+ if test_data_class_name !~ /^RspecTestData::/
17
+ test_data_class_name = "RspecTestData::#{test_data_class_name}"
18
+ end
19
+ parts = test_data_class_name.split(/::/).map(&:underscore)
20
+
21
+ path = (@spec_path / parts[1..-1].join("/")).to_s + ".test_data.rb"
22
+
23
+ if !File.exist?(path)
24
+ raise "Expected to find test data for #{test_data_class_name} in '#{path}', but that file doesn't exist."
25
+ end
26
+
27
+ require_relative path
28
+ test_data_class_name.constantize.new(**args)
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,3 @@
1
+ module RspecTestData
2
+ VERSION="1.0.0.pre1"
3
+ end
@@ -0,0 +1,2 @@
1
+ module RspecTestData
2
+ end
@@ -0,0 +1,27 @@
1
+ require_relative "lib/rspec_test_data/version"
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "rspec_test_data"
5
+ spec.version = RspecTestData::VERSION
6
+ spec.authors = ["Dave Copeland"]
7
+ spec.email = ["davec@naildrivin5.com"]
8
+ spec.summary = %q{Create complex sets of test data using factories to allow re-use across tests or in seed data}
9
+ spec.homepage = "https://sustainable-rails.com"
10
+ spec.license = "Hippocratic"
11
+
12
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.5.0")
13
+
14
+ spec.metadata["homepage_uri"] = spec.homepage
15
+ spec.metadata["source_code_uri"] = "https://github.com/sustainable-rails/rspec_test_data"
16
+ spec.metadata["changelog_uri"] = "https://github.com/sustainable-rails/rspec_test_data/releases"
17
+
18
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
19
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
20
+ end
21
+ spec.bindir = "exe"
22
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
23
+ spec.require_paths = ["lib"]
24
+
25
+ spec.add_development_dependency("rspec")
26
+ spec.add_development_dependency("rspec_junit_formatter")
27
+ end
metadata ADDED
@@ -0,0 +1,94 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec_test_data
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0.pre1
5
+ platform: ruby
6
+ authors:
7
+ - Dave Copeland
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-11-04 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec_junit_formatter
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description:
42
+ email:
43
+ - davec@naildrivin5.com
44
+ executables: []
45
+ extensions: []
46
+ extra_rdoc_files: []
47
+ files:
48
+ - ".circleci/config.yml"
49
+ - ".gitignore"
50
+ - ".rspec"
51
+ - CODE_OF_CONDUCT.md
52
+ - CONTRIBUTING.md
53
+ - Gemfile
54
+ - LICENSE.md
55
+ - README.md
56
+ - Rakefile
57
+ - bin/ci
58
+ - bin/console
59
+ - bin/rspec
60
+ - bin/setup
61
+ - lib/rspec_test_data.rb
62
+ - lib/rspec_test_data/base_test_data.rb
63
+ - lib/rspec_test_data/rspec_setup.rb
64
+ - lib/rspec_test_data/seeds_helper.rb
65
+ - lib/rspec_test_data/version.rb
66
+ - rspec_test_data.gemspec
67
+ homepage: https://sustainable-rails.com
68
+ licenses:
69
+ - Hippocratic
70
+ metadata:
71
+ homepage_uri: https://sustainable-rails.com
72
+ source_code_uri: https://github.com/sustainable-rails/rspec_test_data
73
+ changelog_uri: https://github.com/sustainable-rails/rspec_test_data/releases
74
+ post_install_message:
75
+ rdoc_options: []
76
+ require_paths:
77
+ - lib
78
+ required_ruby_version: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: 2.5.0
83
+ required_rubygems_version: !ruby/object:Gem::Requirement
84
+ requirements:
85
+ - - ">"
86
+ - !ruby/object:Gem::Version
87
+ version: 1.3.1
88
+ requirements: []
89
+ rubygems_version: 3.1.2
90
+ signing_key:
91
+ specification_version: 4
92
+ summary: Create complex sets of test data using factories to allow re-use across tests
93
+ or in seed data
94
+ test_files: []