I am following this pattern
it { is_expected.to respond_to(:cars) } for checking the association
Now accidentally in the model, let's assume I have this line
has_many :bars
So in the test, after seeing the model. I went ahead and did this
it { is_expected.to respond_to(:bars) }
And the test passes, but there is no model Bar how do we rectify this.
has_many :bars adds many methods to your model, bars is one of them, and respond_to matcher just check if there's such publicly available method - so you don't really testing what you think you would like to test.
You could for example do something like this:
expect(subject.bars.build).to be_instance_of(Bar)
This spec would fail if Bar does not exist.
I'm also pretty sure that
expect(subject.bars).to eq []
Would fail too, since it should try to find those in the DB, and missing model would surface here as well.
Also this
expect{ subject.bars.build }.not_to raise_exception
should also fail.
That's generally the problem with dynamic languages - errors (including typos) are not immediately caught.
I actually didn't know that you can define a relation to unexisting model. But it makes sense - checking if the classes exists during the class definition could be a bit too heavy.
I have an answer in a few parts. First, you can help avoid these typos of errors by test-driving your implementation. If you write a failing test first, the error message is another opportunity for you to recognize the typo: "Wait, a minute... it doesn't make sense for this to respond to bars. That's not what I meant..."
The larger answer is that this test on its own has so little value as to be worthless. If you make the typo above in both the implementation and that test and no other test fails then it's hard for me to believe it matters at all if the object response to cars, bars or any other typo.
A more valuable test would exercise the behavior of the association. For instance, if you wanted to test that a Person could associate a Car to their user, you could start with a feature test that exercises that feature. The test failure would guide you toward a working implementation that may or may not require that association. But if you typo the association you will find out because you are testing actual behavior.
Related
I just, manually, discovered a migration error. I added a new field to a model, and forgot to add it into the model_params method of the controller. As a result the new field wasn't persisted to the database.
Easy enough to fix once I noticed the problem, but it got me to wondering if there was a way to detect this in testing. I would imagine something like a gem that would parse the schema and generate a set of tests to ensure that all of the fields could be written and that the same data could be read back.
Is this something that can be (or is) done? So far, my searches have led me to lots of interesting reading, but not to a gem like this...
It is possible to write what you would want. Iterate through all the fields in the model, generate params that mirrors those fields, and then run functional tests on your controllers. The problem is that the test is brittle. What if you don't actually want all the fields to be writable through params? What if you reference a model in another controller outside of the standard pattern? How will you handle generating data that would pass different validations? You would either have to be sure that your application would only be written in a certain way or this test would become more and more complex to handle additional edge cases.
I think the solution in testing would be to try to keep things simple; realize that you've made a change to the system and as a result of that change, corresponding tests would need to be updated. In this case, you would update the functional and unit tests affected by that model. If you were strictly adhering to Test Driven Design, you would actually update the tests first to produce a failing test and then implement the change. As a result, hopefully the updated functional test would have failed in this case.
Outside of testing, you may want to look into a linter. In essence, you're asking if you can catch an error where the parameters passed to an object's method doesn't match the signature. This is more catchable when parsing the code completely (i.e. compilation in a static type environment).
EDIT - I skipped a step on the linting, as you would also have to write your code a certain way that a linter would catch it, such as being more explicit of the method and parameters passed to it.
You might want to consider that such a gem may not exist because its not that practical or useful in real life.
Getting the columns off a model is pretty simple from the reflection methods that Active Record gives you. And yeah you could use that theoretically to automagically run a bunch of tests in loop.
But in reality its just not going to cut it. In real life you don't want every column to be assignable. Thats why you are using mass assignment protection in the first place.
And add to that the complexity of the different kinds of constraints and data types your models have. You'll end up with something extremely complex with just adds a bunch of tests with limited value.
If you find yourself omitting a property from mass assignment protection than your should try to cover that part of your controller either with a functional test or an integration test.
class ArticlesControllerTest < ActionController::TestCase
def valid_attributes
{
title: 'How to test like a Rockstar',
content: 'Bla bla bla'
}
end
test "created article should have the correct attributes" do
post :create, article: valid_attributes
article = Article.last
valid_attributes.keys.each do |key|
assert_equals article[key], valid_attributes[key]
end
end
end
I'm seeing some weird behaviour in FactoryGirl that seems to contradict the documentation. In an Rspec test, if I do this;
static_groups = FactoryGirl.create_list(:static_group,5)
expect(StaticGroup.count).to eq(5)
The test fails (expected: 5, got: 0). If I add in explicit saves of the records;
static_groups = FactoryGirl.create_list(:static_group,5)
static_groups.each do |grp|
grp.save
end
expect(StaticGroup.count).to eq(5)
The test passes! I thought "create" in factorygirl was supposed to do a save for you, but in this case it is plainly not saving records which can be saved straight away afterwards! Even weirder, if I interrogate the objects in the first example (where I don't do an explicit save) they all have ids, so they've definately been talking to the database!!
EDIT
Before anyone points out the dodgy "count" syntax, I'm using DataMapper as an ORM, that's a valid way of counting :)
Ugh - nightmare.
Eventually figured out what it was - the "StaticGroup" class uses STI to figure its type out. This is a little more complex because it hooks into two databases and the class structure changed between legacy and new-world.
Long story short, I copy/pasted my group factory into the static group factory and forgot to change the type. There was a hook in the "save" method that sorts this out for me and it wasn't getting fired when factorygirl created the object.
Listening to Giant Robots Smashing Into Other Giant Robots podcast, I heard that you want your FactoryGirl factories to be minimal, only providing those attributes that make the object valid in the database. That being said, the talk also went on to say that traits are a really good way to define specific behavior based on an attribute that may change in the future.
I'm wondering if it's also a good idea to have traits defined that purposefully fail validations to clean up the spec code. Here's an example:
factory :winner do
user_extension "7036"
contest_rank 1
contest
trait :paid do
paid true
end
trait :unpaid do
paid false
end
trait :missing_user_extension do
user_extension nil
end
trait :empty_user_extension do
user_extension ""
end
end
will allow me to call build_stubbed(:winner, :missing_user_extension) in my specs in tests I intend to fail validations. I suppose I could further this explicit fail by nesting these bad factories under another factory called :invalid_winner, but I'm not too sure if that's necessary. I'm mostly interested in hearing others' opinions on this concept.
No it's not a good idea, it wont make your specs clear to understand after a while, and later when your code evolve those factory that fail today may not fail anymore, and you would have hard time to review all your specs.
It is way better to write your test for one clearly identified thing. If you want to check that saving fails with a mandatory parameter missing, just write it with your regular factory and add parameters to overwrite the values from the factory:
it 'should fail' do
create :winner, user_extension: nil
...
end
With RSpec and Shoulda you can:
it { should belong_to(:product) }
I am told specs should specify observed behavior. This spec also does seem like duplication of code that can be written in the model. So is there a time and place to actually use a test like this?
The bigger question is, why is it bad to test this? If you are told specs should specify observed behaviour, and a model having a belongs_to automatically gives it a method to access the association, is that not something to observe? You could test the #product method instead, but how would that test go?
it "has an association to a product" do
product = Product.create
model = Model.create(:product_id => product.id)
model.product.should eq product
end
Is that really better than just using the single liner?
it { should belong_to(:product) }
If the code is in any way important, you should test it.
Furthermore, if you were following TDD, you would write the test first to specify that an association has to be there, then put in the code to maintain that test.
Say I have an instance method that does many different things that I need to test, something like store#process_order. I'd like to test that it sends an email to the customer, adds an entry in the orders table, charges a credit card, etc. What's the best way to set this up in rspec? Currently, I'm using rspec and factory girl I do something like this:
describe Store do
describe "#process_order" do
before do
#store = Factory(:store)
#order = Factory(:order)
# call the process method
#store.process_order(#order)
end
it 'sends customer an email' do
...
end
it 'inserts order to db' do
...
end
it 'charges credit card' do
...
end
end
end
But it feels really tedious. Is this really the right way to write a spec for a method that I need to make sure does several different things?
Note: I'm not interested in answers about whether or not this is good design. It's just an example I made up to help w/ my question - how to write these types of specs.
This is a good method because you can identify which element is broken if something breaks in the future. I am all for testing things individually. I tend not to check things get inserted into the database as you are then rails functionality. I simply check the validity of the object instead.
This is the method that is used in the RSpec book too. I would certainly recommend reading it if you are unsure about anything related to RSpec.
I think what you are doing is fine and I think it's the way rspec is intended to be used. Every statement (specification) about your app gets its own block.
You might consider using before (:all) do so that the order only has to get processed once but this can introduce dependencies on the order the specs are run.
You could combine all the code inside describe "#process_order" into one big it block if you wanted to, but then it would be less readable and rspec would give you less useful error messages when a spec fails. Go head and add raise to one of your tests and see what a nice error message you can get from rspec if you do it the way you are currently doing it.
If you want to test the entire process then we're talking about an integration test, not a unit test. If you want to test #process_order method which does several things, then I'd expect those things mean calling other methods. So, I would add #should_receive expectations and make sure that all paths are covered. Then I would spec all those methods separately so I have a nice unit spec suite for everything. In the end I would definitely write an integration/acceptance spec which checks if all those pieces are working together.
Also, I would use #let to setup test objects which removes dependencies between spec examples (it blocks). Otherwise a failure of one of the examples may cause a failure in other example giving you an incorrect feedback.