I have the following (simplified) Rails Concern:
module HasTerms extend ActiveSupport::Concern module ClassMethods def optional_agreement # Attributes #---------------------------------------------------------------------------- attr_accessible :agrees_to_terms end def required_agreement # Attributes #---------------------------------------------------------------------------- attr_accessible :agrees_to_terms # Validations #---------------------------------------------------------------------------- validates :agrees_to_terms, :acceptance => true, :allow_nil => :false, :on => :create end end end
I can't figure out a good way to test this module in RSpec however - if I just create a dummy class, I get active record errors when I try to check that the validations are working. Has anyone else faced this problem?
Rails is a development tool which gives web developers a framework, providing structure for all the code they write. The Rails framework helps developers to build websites and applications, because it abstracts and simplifies common repetitive tasks.
Ruby on Rails is used as a backend framework for web applications. It's known for efficiency and scalability. You can write rich functionality with much fewer lines of code as opposed to what you'd need in Java or Node.
Regular web application - Ruby on Rails is still a good solution for regular web applications. If you don't expect millions of users and a huge traffic then Ruby on Rails may be the right choice for you! It is a proven and reliable technology that powers many applications regardless of its downsides.
Rails is a model–view–controller (MVC) framework, providing default structures for a database, a web service, and web pages. It encourages and facilitates the use of web standards such as JSON or XML for data transfer and HTML, CSS and JavaScript for user interfacing.
Check out RSpec shared examples.
This way you can write the following:
# spec/support/has_terms_tests.rb shared_examples "has terms" do # Your tests here end # spec/wherever/has_terms_spec.rb module TestTemps class HasTermsDouble include ActiveModel::Validations include HasTerms end end describe HasTerms do context "when included in a class" do subject(:with_terms) { TestTemps::HasTermsDouble.new } it_behaves_like "has terms" end end # spec/model/contract_spec.rb describe Contract do it_behaves_like "has terms" end
You could just test the module implicitly by leaving your tests in the classes that include this module. Alternatively, you can include other requisite modules in your dummy class. For instance, the validates
methods in AR models are provided by ActiveModel::Validations
. So, for your tests:
class DummyClass include ActiveModel::Validations include HasTerms end
There may be other modules you need to bring in based on dependencies you implicitly rely on in your HasTerms
module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With