Is there a better way to test this Rails controller with RSpec?
source link: https://www.codesd.com/item/is-there-a-better-way-to-test-this-rails-controller-with-rspec.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Is there a better way to test this Rails controller with RSpec?
I have an Account model that validates that its subdomain is unique.
I'm trying to learn how to test controllers with RSpec.
Here's what I've come up with, but it's quite different than the generated RSpec test and i'm wondering if this is a good way to test this or if there's a better way.
My test:
describe "POST create" do
describe "with valid params" do
it "creates a new Account" do
original_count = Account.count
account = FactoryGirl.build(:account, :subdomain => 'newdomain')
post :create, {:account => account}
account.save!
new_count = Account.count
expect(new_count).to eq(original_count + 1)
end
...
EDIT
I forgot to point out the fact that in my spec_helper I have the code below. It is needed because of the way i'm handling subdomains:
config.before(:each, :type => :controller) do
@account = FactoryGirl.create(:account)
@user = FactoryGirl.create(:user)
@request.host = "#{@account.subdomain}.example.com"
sign_in @user
end
There is, by using Rspec's expect to change
, and FactoryGirl's attributes_for
(might need tweaking, not tested):
describe "POST create" do
describe "with valid params" do
it "creates a new Account" do
expect{
post :create, { account: attributes_for(:account) }
}.to change{Account.count}.by(1)
end
...
Validate your unique subdomain constraint in your unit tests, perhaps using shoulda-matchers
:
describe Account do
it { should validate_uniqueness_of(:subdomain) }
end
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK