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.
Related
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.
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
In my opinion and for my purposes, factory_girl completely sucks. Some limitations include:
No debugging support
If I include debugger statements, they are treated as model attributes. Instead of invoking the debugger, I just get strange errors.
FactoryGirl.define do
factory :admin do
name do
debugger # <-- Does not work.
Forgery(:name).full_name
end
email { Forgery(:email).address }
debugger # <-- Does not work either.
password "secret"
end
end
Limitations to associations
Am I too stupid or is there no elegant way to add two posts to a user?
FactoryGirl.define do
factory :post do
title "Foobar"
content "Some content"
end
factory :user do
name { Forgery(:name).full_name }
email { Forgery(:email).address }
# This does not work, if the Post model requires Post#user to be set.
posts [FactoryGirl.create(:post), FactoryGirl.create(:post)]
end
end
See also Factory Girl - Why are Records being continually created?
Tends to trigger strange bugs in rails
I can't remeber what happend, but often strange problems arise with factory_girl.
So given these examples. Are there any alternatives to factory_girl that do not have these issues?
I agree and found Factory Girl overly complicated for what it does.
I wrote a simpler gem a while ago which (at the time at least) was a drop in replacement for Factory Girl-based tests.
The factory definitions use much simpler Ruby and therefore behave as you would expect them to.
Check it out:
https://github.com/ginty/cranky
Why are you debugging inside the factory definition instead of in your code on the resulting objects?
And what's wrong with
user = FactoryGirl.create(:user)
2.times do
FactoryGirl.create(:post, user: user)
end
A debugger statement in a DSL can be problematic. You don't know when it will run.
FactoryGirl could run the DSL, save a representation of the factory, and use the internal representation in memory when the factory is used.
Also, there is no variable to inspect except self. The self is going to be a germ object to build the definition.
At the risk of answers all being defense of FactoryGirl, if your alternatives to FactoryGirl are DSLs to populate data, you are still going to have the problem of debugging support.
Alternatives include fixtures and just calling ActiveRecord to populate test data. Really FactoryGirl doesn't have much over ActiveRecord, it's just more symbol oriented calls, so people get to make meaningful symbol names which is all FactoryGirl was supposed to do.
You cannot put a debugger statement in the middle of a fixture, or in the middle of a hash that you are sending to a create method, but at least you won't be tempted to.
(The See also Factory Girl - Why are Records being continually created?, was an example where FactoryGirl was working perfectly, but the user told it to create four records, and then was surprised when it created four records.)
So maybe if you stick with fixtures and ActiveRecord calls things will be dumbed down enough that you won't get confused.
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.
Should I write unit tests for my associations?
I haven't found many good resources on how and whether to do the testing. I also see/hear some opinion that it is okay to not test your associations (belongs_to and has_many) as they are already tested in rails. And there is another view that says, if it code you write, it is code you test.
So if you say I should, please tell me few good ways of doing this.
Currently, I'm writing tests using Test::Unit and I'm not using Shoulda (I don't have any macros). So for testing each association, I am creating a bunch of objects and then doing asserts on them. Somewhat like this -
For a Post model that has_many comments, my test logic goes this way -
p = Post.create(:title => 'dummy_title', :content => 'lorem ...')
3.times{ Comment.create(:post_id :=> p.id, :commentor => 'jack')}
assert_equal(3, p.comments.size, "post doesn't have correct no of comments")
To me, testing the association borders on testing the language (or in this case, testing the framework).
I'd reserve it for circumstances where you're doing something nonstandard with the association. For example, if every time you create a comment it changes something in the parent post, test that.