Trouble with rspec test with a polymorphic class
I'm using MongoMapper instead of ActiveRecord.
I have a User model and a Task model. In the Task model, I have 2 attributes as follow:
- Owner
- Author
Both attributes are User references.
Here are the relations between the two models:
User.rb
has_many :tasks, :as => :owner
Taks.rb
belongs_to :owner, :class_name => "User", :polymorphic => true
I've used RSpec for writing test: (@user is declared before)
it "should have many tasks" do
another_user = Factory.create(:user, :email => Faker::Internet.email)
开发者_StackOverflow中文版 task_1 = Factory.create(:task, :owner => another_user, :author => another_user)
task_2 = Factory.create(:task, :owner => another_user, :author => @user)
task_3 = Factory.create(:task, :owner => @user, :author => @user)
another_user.tasks.size.should == 2
end
And here is the issue:
Failure/Error: another_user.tasks.size.should == 2
expected: 2
got: 3 (using ==)
However when I do the same in rails console, I get good results...
Here are the factories:
Factory.define :user do |u|
u.first_name 'Test User' #
u.username 'Test User' #
u.surname 'TheTest' #
u.email 'foo@foobar.com' #
u.password 'please' #
u.confirmed_at Time.now #
end
Factory.define :task do |u|
u.author nil #
u.owner nil #
u.subjects []
u.timeframe ""
u.initially_placed_at nil
u.label "Foo Task" #
u.description "A small task description"
u.done false
u.pinned false
u.confidentiality ""
end
There are several answers to this:
1) You may have a leaking spec that runs before this spec (this means that a task is created with the id and type of 'another_user' before this
2) It may be necessary to create the tasks, too (try to use Factory.create(:task) instead of just Factory(:task)
3) You may want to check out shoulda, it helps you spec associations very easily, like this for example:
it { should have_many(:posts) }
That is pretty mind-numbing indeed. I see a few options to help you find this:
use Rubymine, where you can easily debug your tests
add a lot of log-statements
add the following test:
another_user.tasks.should =~ [task1, task2]
This will show the difference in the list of items, and will the other item be task3
?
- i hope your factory does not create a default task for each user?
Aside of that: indeed, checkout shoulda!
精彩评论