Skip to content
Snippets Groups Projects
Commit 1c0a9af7 authored by Anusha Ranganathan's avatar Anusha Ranganathan
Browse files

Setting up factories for rspec

parent 5a0bed07
No related branches found
No related tags found
2 merge requests!19Develop,!3Feature/18 datacite metadata model
FactoryBot.define do
factory :admin_set do
sequence(:title) { |n| ["Title #{n}"] }
# Given the relationship between permission template and admin set, when
# an admin set is created via a factory, I believe it is appropriate to go ahead and
# create the corresponding permission template
#
# This way, we can go ahead
after(:create) do |admin_set, evaluator|
if evaluator.with_permission_template
attributes = { source_id: admin_set.id }
attributes = evaluator.with_permission_template.merge(attributes) if evaluator.with_permission_template.respond_to?(:merge)
# There is a unique constraint on permission_templates.source_id; I don't want to
# create a permission template if one already exists for this admin_set
# create(:permission_template, attributes) unless Hyrax::PermissionTemplate.find_by(source_id: admin_set.id)
create(:permission_template, attributes) unless Hyrax::PermissionTemplate.find_by(source_id: admin_set.id)
# Hyrax::Workflow::WorkflowFactory.create
Hyrax::Workflow::WorkflowImporter.load_workflows
mediated_workflow = admin_set.permission_template.available_workflows.where(name: "nims_mediated_deposit").first
Sipity::Workflow.activate!(permission_template: admin_set.permission_template, workflow_id: mediated_workflow.id)
end
end
transient do
# false, true, or Hash with keys for permission_template
with_permission_template { false }
end
end
end
\ No newline at end of file
FactoryBot.define do
factory :dataset do
transient do
user { create(:user) }
# Set to true (or a hash) if you want to create an admin set
with_admin_set { false }
end
title { ["Dataset"] }
access_control
trait :open do
visibility { 'open' }
title { ["Open Dataset"] }
end
trait :authenticated do
visibility { 'authenticated' }
title { ["Authenticated Dataset"] }
end
trait :embargo do
visibility { 'embargo' }
title { ["Embargo Dataset"] }
end
trait :lease do
visibility { 'lease' }
title { ["Leased Dataset"] }
end
trait :restricted do
visibility { 'restricted' }
title { ["Restricted Dataset"] }
end
trait :with_abstract do
abstract { ["Abstract-Description-123"] }
end
trait :with_abstract_seq do
sequence(:abstract) { |n| ["Abstract-#{n}"] }
end
trait :with_alternative_title do
alternative_title { ['Alternative-Title-123'] }
end
trait :with_keyword do
keyword { ['Keyword-123'] }
end
trait :with_keyword_seq do
sequence(:keyword) { |n| ["Keyword-#{n}"] }
end
trait :with_subject do
subject { ['Subject-123'] }
end
trait :with_subject_seq do
sequence(:subject) { |n| ["Subject-#{n}"] }
end
trait :with_language do
language { ['Faroese'] }
end
trait :with_publisher do
publisher { ['Publisher-123'] }
end
trait :with_resource_type do
resource_type { ['Resource-Type-123'] }
end
trait :with_article_resource_type do
resource_type { ['Article'] }
end
trait :with_source do
source { ['Source-123'] }
end
trait :with_complex_person do
complex_person_attributes {
[{
name: 'Anamika',
role: ['operator'],
orcid: '123456',
affiliation: 'University',
}]
}
end
trait :with_complex_author do
complex_person_attributes {
[{
name: 'Anamika',
role: ['author'],
orcid: '123456',
affiliation: 'University',
}]
}
end
trait :with_detailed_complex_author do
complex_person_attributes {
[{
name: 'Anamika',
first_name: 'First name',
last_name: 'Last name',
email: 'a@example.com',
role: ['author'],
orcid: '23542345234',
affiliation: 'My org'
}]
}
end
trait :with_detailed_complex_people do
complex_person_attributes {
[{
name: 'Anamika',
first_name: 'First name',
last_name: 'Last name',
role: ['author'],
orcid: '123456',
affiliation: 'University',
},
{
name: 'Cee Jay',
first_name: 'First name',
last_name: 'Last name',
role: ['editor'],
orcid: '112233445566',
affiliation: 'My journal org'
}]
}
end
trait :with_complex_date do
complex_date_attributes {
[{
date: '1978-10-28',
description: 'Collected'
}]
}
end
trait :with_complex_identifier do
complex_identifier_attributes {
[{
identifier: '10.0.1111',
scheme: 'DOI'
}]
}
end
trait :with_complex_relation do
complex_relation_attributes {
[{
title: 'A relation label',
url: 'http://example.com/relation',
complex_identifier_attributes: [{
identifier: ['info:hdl/4263537/400'],
scheme: 'identifier persistent'
}],
relationship: 'isNewVersionOf'
}]
}
end
trait :with_rights do
rights_statement {
[
'http://creativecommons.org/publicdomain/zero/1.0/'
]
}
end
trait :with_complex_funding_reference do
complex_funding_reference_attributes {
[{
funder_identifier: 'f1234',
funder_name: 'Bank',
award_number: 'a1234',
award_uri: 'http://example.com/a1234',
award_title: 'No free lunch'
}]
}
end
end
end
FactoryBot.define do
factory :access_control, class: Hydra::AccessControl do
#visibility Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE
#access_rights Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE
skip_create
end
factory :list_source, class: ActiveFedora::Aggregation::ListSource do
skip_create
end
factory :relation, class: ActiveTriples::Relation do
skip_create
end
trait :private do
visibility { Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PRIVATE }
end
end
FactoryBot.define do
factory :file_set do
transient do
user { create(:user) }
content { File.open('spec/fixtures/csv/example.csv', 'r') }
end
after(:build) do |fs, evaluator|
fs.apply_depositor_metadata evaluator.user.user_key
end
after(:create) do |file, evaluator|
Hydra::Works::UploadFileToFileSet.call(file, evaluator.content) if evaluator.content
end
trait :open do
visibility { 'open' }
title { ["Open File Set"] }
end
trait :authenticated do
visibility { 'authenticated' }
title { ["Authenticated File Set"] }
end
trait :embargo do
visibility { 'embargo' }
title { ["Embargo File Set"] }
end
trait :lease do
visibility { 'lease' }
title { ["Leased File Set"] }
end
trait :restricted do
visibility { 'restricted' }
title { ["Restricted File Set"] }
end
trait :long_filename do
visibility { 'open' }
content { File.open('spec/fixtures/csv/ファイル名の長さがエスケープ後に256文字以上になる、長い日本語のファイル名を持つファイル.csv', 'r') }
end
end
end
FactoryBot.define do
trait :override_new_record do
after(:build) do |instance|
# we need to override the new_record? method; otherwise it will check with via the Fedora API and initiate an HTTP call
instance.define_singleton_method(:new_record?) do
true
end
end
end
end
FactoryBot.define do
factory :permission_template, class: Hyrax::PermissionTemplate do
# Given that there is a one to one strong relation between permission_template and admin_set,
# with a unique index on the source_id, I don't want to have duplication in source_id
sequence(:source_id) { |n| format("%010d", n) }
before(:create) do |permission_template, evaluator|
if evaluator.with_admin_set
source_id = permission_template.source_id
admin_set =
if source_id.present?
begin
AdminSet.find(source_id)
rescue ActiveFedora::ObjectNotFoundError
create(:admin_set, id: source_id)
end
else
create(:admin_set)
end
permission_template.source_id = admin_set.id
elsif evaluator.with_collection
source_id = permission_template.source_id
collection =
if source_id.present?
begin
Collection.find(source_id)
rescue ActiveFedora::ObjectNotFoundError
create(:collection, id: source_id)
end
else
create(:collection)
end
permission_template.source_id = collection.id
end
end
after(:create) do |permission_template, evaluator|
if evaluator.with_workflows
Hyrax::Workflow::WorkflowImporter.load_workflow_for(permission_template: permission_template)
Sipity::Workflow.activate!(permission_template: permission_template, workflow_id: permission_template.available_workflows.pluck(:id).first)
end
if evaluator.with_active_workflow
workflow = create(:workflow, active: true, permission_template: permission_template)
create(:workflow_action, workflow: workflow) # Need to create a single action that can be taken
end
AccessHelper.create_access(permission_template, 'user', :manage, evaluator.manage_users) if evaluator.manage_users.present?
AccessHelper.create_access(permission_template, 'group', :manage, evaluator.manage_groups) if evaluator.manage_groups.present?
AccessHelper.create_access(permission_template, 'user', :deposit, evaluator.deposit_users) if evaluator.deposit_users.present?
AccessHelper.create_access(permission_template, 'group', :deposit, evaluator.deposit_groups) if evaluator.deposit_groups.present?
AccessHelper.create_access(permission_template, 'user', :view, evaluator.view_users) if evaluator.view_users.present?
AccessHelper.create_access(permission_template, 'group', :view, evaluator.view_groups) if evaluator.view_groups.present?
end
transient do
with_admin_set { false }
with_collection { false }
with_workflows { false }
with_active_workflow { false }
manage_users { nil }
manage_groups { nil }
deposit_users { nil }
deposit_groups { nil }
view_users { nil }
view_groups { nil }
end
end
class AccessHelper
def self.create_access(permission_template_id, agent_type, access, agent_ids)
agent_ids.each do |agent_id|
FactoryBot.create(:permission_template_access,
access,
permission_template: permission_template_id,
agent_type: agent_type,
agent_id: agent_id)
end
end
end
end
# Based on: https://github.com/samvera/hyrax/blob/master/spec/factories/users.rb
FactoryBot.define do
factory :role do
sequence(:name) { |n| "role-#{n}"}
trait :admin do
name { 'admin' }
end
end
end
FactoryBot.define do
factory :uploaded_file, class: Hyrax::UploadedFile do
file { Rack::Test::UploadedFile.new("#{::Rails.root}/spec/fixtures/image.jp2") }
user_id { 1 }
end
end
# Based on: https://github.com/samvera/hyrax/blob/master/spec/factories/users.rb
FactoryBot.define do
factory :user do
sequence(:email) { |n| "user#{n}@example.com" }
sequence(:username) { |n| "user#{n}" }
sequence(:display_name) { |n| "User #{n}"}
sequence(:user_identifier) { |n| "identifier_#{n}" }
password { 'password' }
transient do
# Allow for custom groups when a user is instantiated.
# @example create(:user, groups: 'avacado')
groups { [] }
end
trait :mock_groups do
# TODO: Register the groups for the given user key such that we can remove the following from other specs:
# `allow(::User.group_service).to receive(:byname).and_return(user.user_key => ['admin'])``
after(:build) do |user, evaluator|
# In case we have the instance but it has not been persisted
::RSpec::Mocks.allow_message(user, :groups).and_return(Array.wrap(evaluator.groups))
# Given that we are stubbing the class, we need to allow for the original to be called
::RSpec::Mocks.allow_message(user.class.group_service, :fetch_groups).and_call_original
# We need to ensure that each instantiation of the admin user behaves as expected.
# This resolves the issue of both the created object being used as well as re-finding the created object.
::RSpec::Mocks.allow_message(user.class.group_service, :fetch_groups).with(user: user).and_return(Array.wrap(evaluator.groups))
end
end
trait :guest do
guest { true }
end
trait :email do
sequence(:display_name) { |n| "Email user #{n}"}
guest { true }
employee_type_code { '60' }
end
trait :admin do
roles { build_list :role, 1, :admin }
guest { false }
employee_type_code { '11' }
end
end
end
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'
require 'support/input_support'
# require 'capybara/rails' # might need to turn this on in future
# require 'capybara/rspec' # might need to turn this on in future
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
......
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'coveralls'
require 'simplecov'
# require 'webdrivers'
require 'sidekiq/testing' # use fake Redis for testing
Coveralls.wear!
SimpleCov.start 'rails' do
# we do not unit test importers, as this is run-once code
add_filter "lib/importers"
# additional code coverage groups for Hyrax
add_group 'Actors', 'app/actors'
add_group 'Forms', 'app/forms'
add_group 'Indexers', 'app/indexers'
add_group 'Inputs', 'app/inputs'
add_group 'Presenters', 'app/presenters'
add_group 'Renderers', 'app/renderers'
add_group 'Services', 'app/services'
end
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# https://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = :random
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
# spec/support/factory_bot.rb
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
end
# RSpec without Rails
RSpec.configure do |config|
config.include FactoryBot::Syntax::Methods
# config.before(:suite) do
# FactoryBot.find_definitions
# end
end
module InputSupport
extend ActiveSupport::Concern
include RSpec::Rails::HelperExampleGroup
end
RSpec.configure do |config|
config.include InputSupport, type: :input
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment