How to create 2 instances using factorymethod

淺唱寂寞╮ 提交于 2019-12-11 15:36:12

问题


I am trying to write a test for my rails application using rspec, I basically want to create two instances

1)a user with counter value 0

2)a user with counter value 5 or more

Here is my factory user code

FactoryBot.define do
  factory :user do
    sequence(:email) { |n| "user#{n}@abc.com" }
    name 'rishabh agarwal'
    password '12345678'
    counter 0
  end
end

In user_controller_spec file I have written

context 'get#redeem' do
  it 'should not redeem the account for points lesser than 5' do
    get :redeem, format: :json,params:{:id=>dummyUser.id}
    expect(JSON.parse(response.body)["message"]).to eq("You cannot redeem your points")
   end

  it 'should redeem the account if points are greater than or equal to 5' do                                       
    get :redeem, format: :json,params:{:id=>dummyUser.id}
    json=JSON.parse(response.body)
    expect(JSON.parse(response.body)["counter"]).to eq(5)
  end
end

While I have used let! to create instance let!(:dummyUser){create :user}


回答1:


This is how I'd structure your tests:

context "get#redeem" do
  before { get :redeem, format: :json, params: { id: user.id } }

  context 'when the user has more than or 5 points' do
    let(:user) { create(:user, counter: 5) }

    it 'redeems the account' do
      json = JSON.parse(response.body)
      expect(json["counter"]).to eq 5
      expect(response.status).to eq 200
    end
  end

  context 'when the user has less than 5 points' do
    let(:user) { create(:user, counter: 4) }

    it 'does not redeem the account' do
      json = JSON.parse(response.body)
      expect(json["message"]).to eq "You cannot redeem your points"
      expect(response.status).to eq 403
    end
  end
end

Few notes:

  • Not sure about the 403 response code, you might wish to use a different one.
  • Consider extracting a method called json_response for your tests that will look something like this:
def json_response
  @json_response ||= JSON.parse(response.body)
end



回答2:


Found a better way .... Just initialize the counter variable with 0 in factory and while using context for more then 5 change the value of counter dummyUser.counter=5 dummyUser.save this will change the value to 5 and which can be used by the test case.




回答3:


you can simply pass attributes in the create method

create(:user, counter: 5)


来源:https://stackoverflow.com/questions/53293719/how-to-create-2-instances-using-factorymethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!