I am new to using Shoulda and don't know where to begin.
One of the things I want to be able to test is when I create a new record for a given Model, the controller is supposed to then create new records for another model that is related.
How do I make this in Shoulda?
Here is what happens when I create a new record for Email:
def create
29 @campaign = Campaign.find(params[:campaign_id])
开发者_如何转开发 30 @email = @campaign.emails.build(params[:email])
31 if @email.save
32 @email.new_todos # create todos across all contacts for this asset
33 flash[:notice] = "Successfully created email."
34 #redirect_to campaign_url(@campaign)
35 redirect_to :back
36 else
37 render :action => 'new'
38 end
39 end
'@email.new_todos" creates new records for model Todo, which is an extension added across all the models, such as Email:
def create
29 @campaign = Campaign.find(params[:campaign_id])
30 @email = @campaign.emails.build(params[:email])
31 if @email.save
32 @email.new_todos # create todos across all contacts for this asset
33 flash[:notice] = "Successfully created email."
34 #redirect_to campaign_url(@campaign)
35 redirect_to :back
36 else
37 render :action => 'new'
38 end
39 end
I would like to slowly start incorporating tests and am picking key types of behavior where it seems likely to break down to learn how to do it.
Thanks.
This example is better suited to a unit test. Although you're triggering the action in a controller, the logic is in the model.
Shoulda adds convenience features to Test::Unit
. Things like contexts and matchers.
I'd test this like so:
context '.new_todos' do setup do @campaign = Campaign.create(:name => 'My Campaign') @email = @campaign.emails.build(:subject => 'Test Campaign Email') @email.save @email.new_todos end should 'generate todos for all contacts' do assert @email.todos.count > 0 end end
Obviously the sample attributes would need to change and you'll want to ensure you're getting the desired result (I guessed and used @email.todos
), but it's a start. I'll be happy to update if you can try that out and see what happens.
To test this in the controller, you'll want a functional or integration test. Functional tests are pretty easy with shoulda, too. That would look something like this:
context 'POST to :create' do setup do @campaign = Campaign.create(:name => 'My Campaign') @email = 'test@test.com' # or whatever data you're expecting post :create, :campaign_id => @campaign.id, :email => @email end should respond_with(:redirect) should redirect_to('/some/path') end
That's a start. Good luck!
精彩评论